python - 在 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
等?
解决方案
python3.7
保留dict
插入顺序。所以我们可以按值对字典项进行排序,然后在 new 中插入(或创建)dict
。
采用:
print(dict(sorted(wordlist.items(), key = lambda x: -x[1])))
推荐阅读
- rest - 从 Delphi REST 服务器返回具有计算字段的数据集
- javascript - 做了react.js,Chrome扩展失去焦点,如何强制弹窗强制重新渲染
- hive - 如何在 Hive 中转换不同时区的时间戳
- html - 如何使用 excel 宏将多个网页保存为 pdf 文件或屏幕截图?
- javascript - 如果它是构造函数,如何调用 Object 上的方法?
- sql - 如何在 postgresql 中的 2 列上选择不同的值
- python - Python:为用户名创建“秘密 ID”
- word2vec - Word2Vec 是仅用于句子中的单词还是用于特征?
- javascript - 从随机选择的数组中删除重复项
- c# - Transient Polly 重试不适用于 HttpResponseMessage