gpt4 book ai didi

Python 字数统计和排名

转载 作者:太空狗 更新时间:2023-10-30 00:41:44 26 4
gpt4 key购买 nike

在 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'

谢谢

注意

完整的工作代码:

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 中,在您之前使用 iteritems 的地方仅使用 items

items()返回 dictionary view object支持迭代以及 lenin

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


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

关于Python 字数统计和排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7888786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com