Data Science Micro
Published in

Data Science Micro

Word count in a sentence: it’s complicated

To get the count of words in a sentence you can use Counter from collections module.

# import Counter
from collections import Counter
# sample sentence
sentence = 'here I am and there I am'
# split sentence into words
sentence = sentence.split(' ')
# count words
Counter(sentence
>> Counter({'here': 1, 'I': 2, 'am': 2, 'and': 1, 'there': 1})

Let’s spice things up a little bit and add punctuation in the sentence.

sentence = 'here I am, and there I am'

Try running the same code using this sentence instead and see if the results are the same!!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store