Words count in a sentence in Python
### counting number of words in Python-
This requires use of counter from collection package, Also as split can be used only on strings, one needs to convert list into str.
from collections import Counter
sentence= ['Data science is growing field but buzz is also around and This is hyped']
splitted_sentence= sentence[0].split(" ") # we will get str from list and then split would work, split doesn't work on list
count_word= Counter()
for i in splitted_sentence:
count_word[i]+= 1 # these are like dictionary, can be used to count words etc
print(count_word)
output is-
Counter({'is': 3, 'and': 1, 'hyped': 1, 'growing': 1, 'around': 1, 'field': 1, 'science': 1, 'buzz': 1, 'Data': 1, 'also': 1, 'but': 1, 'This': 1})
Thus we get the count of all the unique words.
can you try list comprehension for the same?
Comments
Post a Comment