繁体   English   中英

打印 Python 中字典的出现从高到低

[英]Print from High to Low occurrences of Dictionary in 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)

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

这是一个测试文件。

hello my friend. hello sir.

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

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

利用:

print(dict(sorted(wordlist.items(), key = lambda x: -x[1])))
from pathlib import Path
from collections import Counter
import string
filepath = Path('test.txt')
# print(filepath.exists())
with open(filepath) as f:
    content = f.readlines()

word_list = sum((
    (s.strip('\n').translate(str.maketrans('', '', string.punctuation))).split(' ')
    for s in content
), [])

for key,value in Counter(word_list).items():
    print(f'{key} : {value}')



暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM