use*_*645 2 python sorting dictionary
为什么我一直这样
AttributeError: 'dict_keys' object has no attribute 'sort'
Run Code Online (Sandbox Code Playgroud)
还是我的代码?我怎样才能解决这个问题?
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()
Run Code Online (Sandbox Code Playgroud)
我不知道还能做什么.
要生成已排序的键列表,请使用:
word_keys = sorted(counts)
Run Code Online (Sandbox Code Playgroud)
代替.这适用于Python 2和3.
在Python 3 dict.keys()中,不返回列表对象,而是返回字典视图对象.您可以调用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]))
Run Code Online (Sandbox Code Playgroud)
此代码使用文件对象作为上下文管理器(使用with语句)自动关闭它们.该Counter.most_common()方法负责为我们排序,而不是按键,而是按字数统计.