Working on a word occurrence count application in a Python 3.2 / Windows environment.
Can anyone please help to tell me why the following isn’t working?
from string import punctuation
from operator import itemgetter
N = 100
words = {}
words_gen = (word.strip(punctuation).lower() for line in open("poi_run.txt")
for word in line.split())
for word in words_gen:
words[word] = words.get(word, 0) + 1
top_words = (words.iteritems(), key=itemgetter(1), reverse=True)[:N]
for word, frequency in top_words:
print ("%s %d") % (word, frequency)
The trace back error is:
Message File Name Line Position
Traceback
<module> C:\Users\will\Desktop\word_count.py 13
AttributeError: 'dict' object has no attribute 'iteritems'
Thanks
n.b.
Fully working code:
from string import punctuation
from operator import itemgetter
N = 100
words = {}
words_gen = (word.strip(punctuation).lower() for line in open("poi_run.txt")
for word in line.split())
for word in words_gen:
words[word] = words.get(word, 0) + 1
top_words = sorted(words.items(), key=itemgetter(1), reverse=True)[:N]
for word, frequency in top_words:
print ("%s %d" % (word, frequency))
Thanks again guys
In Python 3, use just
itemswhere you’d previously useiteritems.The new
items()returns a dictionary view object that supports iteration as well aslenandin.And of course, in
top_words = (words.iteritems(), ...you forgot to call thesortedfunction.Edit: Please see my other answer for a better solution.