在Python 3.2/Windows环境中处理单词出现计数应用程序。

谁能帮我告诉我以下原因为何不起作用?

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)

追溯错误为:
Message File Name   Line    Position
Traceback
    <module>    C:\Users\will\Desktop\word_count.py 13
AttributeError: 'dict' object has no attribute 'iteritems'

谢谢

n.b.

完整的工作代码:
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))

再次感谢你们

最佳答案

在Python 3中,仅使用items,而以前使用iteritems

新的 items() 返回一个支持迭代的dictionary view object以及lenin

当然,在top_words = (words.iteritems(), ...中,您忘记了调用sorted函数。

编辑:请参阅我的其他答案,以获得更好的解决方案。

10-02 08:16