首页 > 解决方案 > 在 Python 中从高到低的字典出现次数打印

问题描述

我有一个代码可以计算文件中的每个单词并计算它们出现的次数。

filename = "test.txt"

output = []

with open(filename) as f:
    content = f.readlines()

content = [x.strip() for x in content]

wordlist = {}

for line in content:
    for entry in line.split():
        word = entry.replace('.', '')
        word = word.replace(',', '')
        word = word.replace('!', '')
        word = word.replace('?', '')

        if word not in wordlist:
            wordlist[word] = 1
        else:
            wordlist[word] = wordlist[word] + 1

print(wordlist)

但是,当我打印这个时,我无法指定从高到低出现。

这是一个测试文件。

hello my friend. hello sir.

如何打印使其看起来像 hello: 2 (newline) my: 1 等?

标签: pythonpython-3.x

解决方案


python3.7保留dict插入顺序。所以我们可以按值对字典项进行排序,然后在 new 中插入(或创建)dict

采用:

print(dict(sorted(wordlist.items(), key = lambda x: -x[1])))

推荐阅读