统计列表中单词的频率并按频率排序

2024-03-28 13:44:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python3.3

我需要创建两个列表,一个用于唯一的单词,另一个用于单词的频率。

我必须根据频率列表对唯一的单词列表进行排序,以便频率最高的单词位于列表的第一位。

我有文本设计,但不确定如何在Python中实现它。

到目前为止,我发现的方法要么使用Counter,要么使用我们尚未学习过的词典。我已经从包含所有单词的文件中创建了列表,但不知道如何查找列表中每个单词的频率。我知道我需要一个循环来做这件事,但我想不出来。

基本设计如下:

 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 

Tags: the方法in文本列表排序counter单词
3条回答
words = file("test.txt", "r").read().split() #read the words into a list.
uniqWords = sorted(set(words)) #remove duplicate words and sort
for word in uniqWords:
    print words.count(word), word

你可以用

from collections import Counter

它支持Python 2.7,阅读更多信息here

一。

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

使用dict

>>>d={1:'one', 2:'one', 3:'two'}
>>>c = Counter(d.values())
[('one', 2), ('two', 1)]

但是,你必须先读取文件,然后转换成dict

2。 这是python文档示例,使用re和Counter

# Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

用这个

from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})

相关问题 更多 >