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

时间:2013-12-11 04:50:47

标签: python python-3.x list frequency word

我正在使用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 

13 个答案:

答案 0 :(得分:118)

使用此

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

答案 1 :(得分:38)

您可以使用

from collections import Counter

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

1

>>>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 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)]

答案 2 :(得分: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

答案 3 :(得分:3)

你可以使用reduce() - 一种功能方式。

preparemandatoryfield()

返回:

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

答案 4 :(得分:2)

一种方法是制作一份清单清单,新清单中的每个子清单都包含一个单词和一个计数:

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])

或者,更有效率:

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

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

答案 5 :(得分:2)

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

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

答案 6 :(得分:1)

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

答案 7 :(得分:1)

使用Counter是最好的方法,但是如果你不想这样做,你可以用这种方式自己实现。

# The list you already have
word_list = ['words', ..., 'other', 'words']
# Get a set of unique words from the list
word_set = set(word_list)
# create your frequency dictionary
freq = {}
# iterate through them, once per unique word.
for word in word_set:
    freq[word] = word_list.count(word) / float(len(word_list))

freq将以你已经拥有的列表中每个单词的频率结束。

你需要float将其中一个整数转换为浮点数,因此得到的值将是一个浮点数。

编辑:

如果你不能使用字典或集合,这是另一种效率较低的方法:

# The list you already have
word_list = ['words', ..., 'other', 'words']
unique_words = []
for word in word_list:
    if word not in unique_words:
        unique_words += [word]
word_frequencies = []
for word in unique_words:
    word_frequencies += [float(word_list.count(word)) / len(word_list)]
for i in range(len(unique_words)):
    print(unique_words[i] + ": " + word_frequencies[i])

unique_wordsword_frequencies的指示将匹配。

答案 8 :(得分:0)

试试这个:

script

答案 9 :(得分:0)

这是代码支持您的问题 is_char()检查验证字符串是否仅对那些字符串进行计数,Hashmap是python中的字典

def is_word(word):
   cnt =0
   for c in word:

      if 'a' <= c <='z' or 'A' <= c <= 'Z' or '0' <= c <= '9' or c == '$':
          cnt +=1
   if cnt==len(word):
      return True
  return False

def words_freq(s):
  d={}
  for i in s.split():
    if is_word(i):
        if i in d:
            d[i] +=1
        else:
            d[i] = 1
   return d

 print(words_freq('the the sky$ is blue not green'))

答案 10 :(得分:0)

熊猫回答:

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

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

pd.Series(original_list).value_counts().sort_values(ascending=True)

答案 11 :(得分:0)

for word in original_list:
   words_dict[word] = words_dict.get(word,0) + 1

sorted_dt = {key: value for key, value in sorted(words_dict.items(), key=lambda item: item[1], reverse=True)}

keys = list(sorted_dt.keys())
values = list(sorted_dt.values())
print(keys)
print(values)

答案 12 :(得分:-2)

最好的办法是:

def wordListToFreqDict(wordlist):
    wordfreq = [wordlist.count(p) for p in wordlist]
    return dict(zip(wordlist, wordfreq))

然后尝试:            wordListToFreqDict(originallist)