python-计算列表中单词的频率并按频率排序
我正在使用Python 3.3
我需要创建两个列表,一个用于唯一词,另一个用于词频。
我必须根据频率列表对唯一单词列表进行排序,以便频率最高的单词在列表中排在第一位。
我有文本设计,但不确定如何在Python中实现它。
到目前为止,我发现的方法是使用2563584570528628629760或我们尚未学习的字典。 我已经从包含所有单词的文件中创建了列表,但是不知道如何找到列表中每个单词的出现频率。 我知道我将需要循环来执行此操作,但无法弄清楚。
基本设计如下:
original list = ["the", "car",....]
newlst = []
frequency = []
for word in the original list
if word not in newlst:
newlst.append(word)
set frequency = 1
else
increase the frequency
sort newlst based on frequency list
12个解决方案
116 votes
用这个
from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})
Ashif Abdulrahman answered 2019-10-10T20:28:14Z
38 votes
您可以使用
from collections import Counter
它支持Python 2.7,在这里阅读更多信息
1。
>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
使用字典
>>>d={1:'one', 2:'one', 3:'two'}
>>>c &