以下代码会打印出txt文件中的单词以及该单词出现的次数(例如,a,26)。问题在于它没有按字母顺序打印。非常感谢您提供任何帮助。
import re
def print_word_counts(filename):
s=open(filename).read()
words=re.findall('[a-zA-Z]+', s)
e=[x.lower() for x in (words)]
e.sort()
from collections import Counter
dic=Counter(e)
for key,value in dic.items():
print (key,value)
print_word_counts('engltreaty.txt')
items()
是一个由2元组(键值对)组成的可迭代对象。这些2元组将按字典顺序排序。首先按键排序(如果有相同的键,则比较值)。当然,由于这是一个字典,我们的键是唯一的...我不确定你所说的“整个键值对按字母顺序排序”的意思是什么,也许可以尝试使用sorted(dic.items(), key=lambda x: x[0] + x[1])
? - mgilson