Python:统计列表中单词的频率

对于程序分配,我需要计算文件中单词的频率。 我一直在寻找这个网站和其他人的帮助,但是他们展示的方法是我们没有在课堂上学到的,所以我不能使用它们。 到目前为止,我发现的方法使用了我们还没有学到的计数器或字典。 我已经从包含所有单词的文件中创build了列表,但不知道如何find列表中每个单词的频率。 我知道我将需要一个循环来做到这一点,但无法弄清楚。 任何帮助将不胜感激。 谢谢。

编辑:所以事实certificate,我需要创build两个名单,一个为独特的话,另一个为单词的频率。 我将不得不根据频率列表对唯一的单词列表进行sorting,使得频率最高的单词在列表中排在第一位。 我在文本中有devise,但仍然有点不确定如何在Python中实现它,所以我将能够正确地sorting列表。 我正在使用Python 3.3

这是基本的devise:

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 

用这个

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

您可以使用

 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 = Counter(d.values()) [('one', 2), ('two', 1)] 

但是,你必须先阅读文件,并转换为字典。

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

你可以使用reduce() – 一种function方式。

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

收益:

 {'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 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]) 

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

想法的方法是使用一个字典映射到它的计数字。 但是,如果你不能使用它,你可能想要使用2个列表–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将匹配。

另一个解决scheme与另一个algorithm没有使用集合:

 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 

最好的办法是:

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

然后尝试: wordListToFreqDict(originallist)

尝试这个:

 words = [] freqs = [] for line in sorted(original list): #takes all the lines in a text and sorts them line = line.rstrip() #strips them of their spaces if line not in words: #checks to see if line is in words words.append(line) #if not it adds it to the end words freqs.append(1) #and adds 1 to the end of freqs else: index = words.index(line) #if it is it will find where in words freqs[index] += 1 #and use the to change add 1 to the matching index in freqs