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!!