[Tutor] Re: count words

Brian Beck exogen at gmail.com
Tue Feb 15 17:51:34 CET 2005


Ron Nixon wrote:
> 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
> 
> etc.

Someone else might offer a better way of finding such information in a 
file, but for now I'll assume that this method is okay and just answer 
your original question. I'd do it like this (untested):

f = open('text.txt').read()
words = ['word', 'beef', 'nachos', 'recipe']

# This makes a list of tuples like [('word', 5), ('beef', 0), ...]
# You might also consider using a dictionary.
count = [(word, f.count(word)) for word in words]

# Now print the results.
for result in count:
    print "%s was found %d times." % result

# Dictionary method:
# Uses the same list comprehension, maybe there's a better way?
count = dict([(word, f.count(word)) for word in words])

for key, value in count.iteritems():
     print "%s was found %d times." % (key, value)

--
Brian Beck
Adventurer of the First Order



More information about the Tutor mailing list