为什么我要继续
AttributeError: 'dict_keys' object has no attribute 'sort'
还是我的代码?我该如何解决这个问题?
import string
infile = open('alice_in_wonderland.txt', 'r')
text = infile.readlines()
counts = {}
for line in text:
for word in line:
counts[word] = counts.get (word, 0) +1
'''
if word != " ":
if word != ".":
'''
word_keys = counts.keys()
word_keys.sort()
infile.close()
outfile = open("alice_words.txt", 'w')
outfile.write("Word \t \t Count \n")
outfile.write("======================= \n")
for word in word_keys:
outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
outfile.close()
我不知道还能做什么。
答案 0 :(得分:8)
要生成已排序的键列表,请使用:
word_keys = sorted(counts)
代替。这适用于Python 2和3。
在Python 3中dict.keys()
不返回列表对象,而是返回dictionary view object。您可以在该对象上拨打list()
,但sorted()
更直接,可以为您节省两次额外的电话。
我看到你似乎计算文件中的单词;如果是这样,你就是计算字符,而不是单词; for word in line:
遍历一个字符串,因此word
会从该行分配单个字符。
您应该使用collections.Counter()
代替:
from collections import Counter
counts = Counter
with open('alice_in_wonderland.txt') as infile:
for line in infile:
# assumption: words are whitespace separated
counts.update(w for w in line.split())
with open("alice_words.txt", 'w') as outfile:
outfile.write("Word \t \t Count \n")
outfile.write("======================= \n")
for word, count in counts.most_common():
outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
此代码使用文件对象作为上下文管理器(使用with
语句)自动关闭它们。 Counter.most_common()
方法负责为我们排序,而不是按键,而是按字数计算。