Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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:
        try:
            d[word] += 1
        except:
            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.

like image 260
Varun Avatar asked Jul 02 '12 20:07

Varun


People also ask

How do you calculate a word count?

One way to specify word count is to count characters and divide by five. If you still need this old-fashioned way of counting, here's how you can let Word do the heavy calculating for you. You can use Word's built in tools to figure out how many words are in your document.


1 Answers

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

input_string.count("Hello")

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

from collections import Counter

words = input_string.split()
wordCount = Counter(words)
like image 80
Joel Cornett Avatar answered Sep 24 '22 12:09

Joel Cornett