[Tutor] counting in a file

Magnus Lycka magnus@thinkware.se
Mon Nov 18 02:50:03 2002


At 18:54 2002-11-17 -0500, reavey wrote:
>I'm trying to count the number of times a word occurs in a file.

Untested...

wordCount = {}

for word in open(filename).read().split():
     if not wordCount.has_key(word):
         wordCount[word] = 0
     wordCount[word] += 1

for entry in wordCount.items():
     print "%s orrurs %i times" % entry


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se