Counter()为所有单词返回1。如何获得实际数量?

时间:2017-08-08 04:23:18

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

我有一个文本文件,我试图获取最常用的单词。我使用的是Counter,但它似乎每个都会返回1

我正在学习,所以我使用Simple Sabotage Field Manual作为我的文本文件。

import re
from collections import Counter
my_file = "fieldManual.txt"

#### GLOBAL VARIABLES
lst = [] # used in unique_words
cnt = Counter()

#########

def clean_word(the_word):
    #new_word = re.sub('[^a-zA-Z]', '',the_word)
    new_word = re.sub('^[^a-zA-z]*|[^a-zA-Z]*$', '', the_word)
    return new_word

def unique_words():
    with open(my_file, encoding="utf8") as infile:
        for line in infile:
            words = line.split()
            for word in words:
                edited_word = clean_word(word)
                if edited_word not in lst:
                    lst.append(edited_word)
                    cnt[edited_word] += 1
    lst.sort()  
    word_count = Counter(lst)
    return(lst)
    return (cnt)

unique_words()
test = ['apple','egg','apple','banana','egg','apple']
print(Counter(lst)) # returns '1' for everything
print(cnt) # same here

所以,print(Counter(test))正确地返回

  

专柜({' apple':3,' egg':2,' banana':1})

但我尝试在lst中打印最常用的字词

  

专柜({'':1,' A':1,'实际':1,'同意':1, '协议':1,' AK':1,'和':1,'任何':1,'任何'任何' 39;:1,' AR':1,' AS-IS':1,' ASCII':1,'关于':1 ,'摘要':1,'意外地':1,'行动':1,'行为':1,'添加& #39;:1,'其他':1,'调整':1,'提倡':1,'':':1, '农业':1,......

在回答from here之后,我尝试在cnt.Update(edited_word)中添加if edited_word not in lst:,但随后打印cnt我只获得单个字符:

  

反击({' e':2401,'我':1634,' t':1470,'':1467, ' n':1455,'':1442,' a':1407,' o':1244,' l&# 39;:948,'':862,' d':752,' u':651,' p':590,& #39; g':564,' m':436,...

如何从.txt文件中返回每个唯一单词的频率?

2 个答案:

答案 0 :(得分:1)

如果尚未找到该字词,则只会将该字词附加到列表中。因此,每个单词只会出现一次。

答案 1 :(得分:1)

这里有一些问题。您应该递增计数器,无论该单词是否在列表中,或者只是从拆分字符串中调用列表上的计数器。你有背对背的返回语句(第二个不会被执行)。您正在使用word_count查找列表的计数,然后忽略该输出(对于每个单词也将为1)。只是清理这段代码可能有助于解决问题。