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

use*_*605 61 python list frequency cpu-word python-3.x

我使用的是Python 3.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 
Run Code Online (Sandbox Code Playgroud)

小智 131

用这个

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

  • 恒星溶液 (2认同)

tdo*_*ong 38

您可以使用

from collections import Counter
Run Code Online (Sandbox Code Playgroud)

它支持Python 2.7,在这里阅读更多信息

1.

>>>c = Counter('abracadabra')
>>>c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Run Code Online (Sandbox Code Playgroud)

用dict

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

但是,您必须先读取文件,然后转换为dict.

2.这是python docs的例子,使用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)]
Run Code Online (Sandbox Code Playgroud)


kyl*_*e k 16

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
Run Code Online (Sandbox Code Playgroud)

  • 你用大文件测试代码吗?如果文件太大,则会花费大量时间.收集更有效率. (5认同)

小智 11

熊猫回答:

import pandas as pd
original_list = ["the", "car", "is", "red", "red", "red", "yes", "it", "is", "is", "is"]
pd.Series(original_list).value_counts()
Run Code Online (Sandbox Code Playgroud)

如果你想按升序排列,它很简单:

pd.Series(original_list).value_counts().sort_values(ascending=True)
Run Code Online (Sandbox Code Playgroud)


Rez*_*tin 8

不使用集合的另一种算法的另一种解决方案:

def countWords(A):
   dic={}
   for x in A:
       if not x in  dic:        #Python 2.7: if not dic.has_key(x):
          dic[x] = A.count(x)
   return dic

dic = countWords(['apple','egg','apple','banana','egg','apple'])
sorted_items=sorted(dic.items())   # if you want it sorted
Run Code Online (Sandbox Code Playgroud)


Mil*_*ica 5

一种方法是创建一个列表列表,新列表中的每个子列表都包含一个单词和一个计数:

list1 = []    #this is your original list of words
list2 = []    #this is a new list

for word in list1:
    if word in list2:
        list2.index(word)[1] += 1
    else:
        list2.append([word,0])
Run Code Online (Sandbox Code Playgroud)

或者,更有效的是:

for word in list1:
    try:
        list2.index(word)[1] += 1
    except:
        list2.append([word,0])
Run Code Online (Sandbox Code Playgroud)

这比使用字典效率低,但它使用了更多基本概念。


Gad*_*adi 5

您可以使用reduce() - 一种函数式方法。

words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})
Run Code Online (Sandbox Code Playgroud)

返回:

{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}
Run Code Online (Sandbox Code Playgroud)


KGo*_*KGo 1

理想的方法是使用字典将单词映射到它的计数。但如果您不能使用它,您可能需要使用 2 个列表 - 1 个存储单词,另一个存储单词计数。请注意,单词和计数的顺序在这里很重要。实施这一点会很困难而且效率不高。