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

dgcosgrave at gmail.com dgcosgrave at gmail.com
Wed Dec 19 05:45:13 EST 2012


Hi Iam just starting out with python...My code below changes the txt file into a list and add them to an empty dictionary and print how often the word occurs, but it only seems to recognise and print the last entry of the txt file. Any help would be great.

tm =open('ask.txt', 'r')
dict = {}
for line in tm:
	line = line.strip()
	line = line.translate(None, '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
	line = line.lower()
	list = line.split(' ')
for word in list:	
		if word in dict:
			count = dict[word]
			count += 1
			dict[word] = count
else:
	dict[word] = 1
for word, count in dict.iteritems():
	print word + ":" + str(count)



More information about the Python-list mailing list