将字典的输出按字母顺序排列

19
以下代码会打印出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')
2个回答

43

您只需要对项目进行排序即可。内置的sorted应该非常有效:

for key,value in sorted(dic.items()):
    ...

如果您删除e.sort()这行代码,那么程序大致上应该以相同的时间运行。它不能正常工作的原因是字典基于hash表存储项,其顺序是根据它们的哈希值(当哈希冲突发生时还有一些更复杂的事情)排序的。由于哈希函数在任何地方都没有被指定,这意味着您无法指望字典保留您尝试给它的任何顺序,并且顺序取决于实现和版本。对于其他简单情况,collections模块具有一个OrderedDict子类,它确实保留插入顺序,但这在这里并不能真正帮助您。


只是这样:sorted(dic.items()) 对我有用,谢谢。 - user1552586
我不仅想要键,还想整个按字母顺序排序的键值对。 - Akin Hwan
1
@AkinHwan -- 我不确定我理解这个问题... items() 是一个由2元组(键值对)组成的可迭代对象。这些2元组将按字典顺序排序。首先按键排序(如果有相同的键,则比较值)。当然,由于这是一个字典,我们的键是唯一的...我不确定你所说的“整个键值对按字母顺序排序”的意思是什么,也许可以尝试使用sorted(dic.items(), key=lambda x: x[0] + x[1])? - mgilson

0
注意,Counterdict 的子类,因此在添加到 Counter 之前进行排序:
e.sort()
dic=Counter(e)

无法实现排序。

import re
from collections import Counter

def print_word_counts(filename):
    c = Counter()
    with open(filename) as f: # with block closes file at the end of the block
        for line in f: # go line by line, don't load it all into mem at once
            c.update(w.lower() for w in re.findall('[a-zA-Z]+', line))

    for k, v in sorted(c.items()): # sorts
        print k, v

print_word_counts('engltreaty.txt')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接