[Tutor] count words

Bill Mill bill.mill at gmail.com
Tue Feb 15 17:50:16 CET 2005


<snip>is there a way to do it so
> that I get a individual count of each word:
> word1 xxx
> word2 xxx
> words xxx
> etc.

Ron, I'm gonna throw some untested code at you. Let me know if you
understand it or not:

word_counts = {}
for line in f:
    for word in line.split():
        if word in word_counts:
            word_counts[word] += 1
            word_counts[word] = 1

for word in word_counts:
    print "%s %d" % (word, word_counts[word])

Bill Mill
bill.mill at gmail.com

More information about the Tutor mailing list