我需要使用dict方法找到5个最常用的单词,还有穆迪系统提供的单词

问题描述 投票:0回答:1
import sys  
girdi = sys.stdin.read()
girdi = girdi.lower()
girdi = girdi.replace('.','')
girdi = girdi.replace(',','')
girdi = girdi.replace("'","")
girdi = girdi.replace("-",' ')
sözlük={}
for word in girdi.split():
    if word not in sözlük:
        sözlük[word] = 1
    else:
        sözlük[word] += 1
for key in sorted(sözlük, key=sözlük.get, reverse=True): 

girdi =输入&sözlük=字典希望我在反驳方面做得很好,但在返回5个最常用的单词时遇到问题。所以我该怎么做 ?

python-3.x
1个回答
0
投票

这应该可以解决问题:

from collections import Counter
import re

#instead of all the replacing - do this on your raw data:
x=Counter(re.findall("\w+", girdi))

#top 5 values:
y=sorted(x.values(), reverse=True)[:5]

#top 5 words, along with respective counts
res=dict(filter(lambda z: z[1] in y, x.items()))

#to get the words only:
res.keys()
© www.soinside.com 2019 - 2024. All rights reserved.