[Tutor] count words

Ryan Davis ryan at acceleration.net
Tue Feb 15 17:51:57 CET 2005

You could use split() to split the contents of the file into a list of strings.

>>> x = 'asdf foo bar foo'
>>> x.split()
['asdf', 'foo', 'bar', 'foo']

Here's one way to iterate over that to get the counts.  I'm sure there are dozens.
>>> x = 'asdf foo bar foo'
>>> counts = {}
>>> for word in x.split():
...	counts[word] = x.count(word)
>>> counts
{'foo': 2, 'bar': 1, 'asdf': 1}
The dictionary takes care of duplicates.  If you are using a really big file, it might pay to eliminate duplicates from the list
before running x.count(word)


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Ron Nixon
Sent: Tuesday, February 15, 2005 11:22 AM
To: tutor at python.org
Subject: [Tutor] count words

I know that you can do this to get a count of home
many times a word appears in a file

f = open('text.txt').read()
print f.count('word')

Other than using a several print statments to look for
seperate words like this, is there a way to do it so
that I get a individual count of each word:

word1 xxx
word2 xxx
words xxx


Do you Yahoo!? 
Yahoo! Mail - Find what you need with new enhanced search.
Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list