counting how often the same word appears in a txt file...But my code only prints the last line entry in the txt file

Thomas Bach thbach at students.uni-mainz.de
Wed Dec 19 12:21:57 CET 2012


Hi,

just as a side-note

On Wed, Dec 19, 2012 at 02:45:13AM -0800, dgcosgrave at gmail.com wrote:
> for word in list:	
> 		if word in dict:
> 			count = dict[word]
> 			count += 1
> 			dict[word] = count
> else:
> 	dict[word] = 1

When you got the indentation and names right, you can restate this as

import collections
counter = collections.Counter(words)

in Python 2.7 or as

import collections
counter = collections.defaultdict(int)
for word in words:
    counter[word] += 1

in Python 2.6

Regards,
	Thomas.



More information about the Python-list mailing list