Varun Varun - 1 year ago 69
Python Question

How to find the count of a word in a string?

I have a string "

Hello I am going to I with hello am
". I want to find how many times a word occur in the string. Example hello occurs 2 time. I tried this approach that only prints characters -

def countWord(input_string):
d = {}
for word in input_string:
d[word] += 1
d[word] = 1

for k in d.keys():
print "%s: %d" % (k, d[k])
print countWord("Hello I am going to I with Hello am")

I want to learn how to find the word count.

Answer Source

If you want to find the count of an individual word, just use count:


Use collections.Counter and split() to tally up all the words:

from collections import Counter

words = input_string.split()
wordCount = Counter(words)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download