【发布时间】:2015-12-05 22:05:16
【问题描述】:
我正在尝试读取一个文本文件,然后打印出所有最常用单词在顶部的单词,随着列表的下降而减少。我有 Python 3.3.2。
def wordCounter(thing):
# Open a file
file = open(thing, "r+")
newWords={}
for words in file.read().split():
if words not in newWords:
newWords[words] = 1
else:
newWords[words] += 1
for k,v in frequency.items():
print (k, v)
file.close()
现在,它确实会按照我想要的 /way/ 打印出所有内容,但是有些单词的使用量比列表中较低的其他单词多。我试过使用 newWords.sort(),但它说:
"AttributeError: 'dict' object has no attribute 'sort'"
所以我无所适从,因为我的知识非常有限。
【问题讨论】:
-
输入文件是什么样的?
-
字典没有
sort(),但您可以将它们传递给sorted()。