On Wednesday, December 19, 2012 11:55:28 PM UTC+13, Jussi Piitulainen wrote: > > > > > > 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) > > > > The "else" clause is mis-indented (rather, mis-unindented). > > > > Python's "for" statement does have an optional "else" clause. That's > > why you don't get a syntax error. The "else" clause is used after the > > loop finishes normally. That's why it catches the last word.
Thanks for quick reply Jussi...indentation fixed the problem :-) -- http://mail.python.org/mailman/listinfo/python-list