繁体   English   中英

按 python 列表统计字频

[英]Counting word frequency by python list

今天我试图编写一个代码来返回一个单词在文本中重复的次数(txt 文件包含的文本)。 起初,在我使用字典之前,我想测试列表是否有效并且单词是否附加到其中,所以我编写了以下代码:

def word_frequency(file) :
    
    """Returns the frequency of all the words in a txt file"""
    
    with open(file) as f :
        
        arg = f.readlines()
        
        l = []
        
        for line in arg :
            l = line.split(' ')
            
            return l

在我给它文件地址并按下 f5 之后,发生了这种情况:

In[18]: word_frequency("C:/Users/ASUS/Desktop/Workspace/New folder/tesst.txt")

Out[18]: ['Hello', 'Hello', 'Hello\n']
  • 一开始你可能认为这个output没有问题,但是txt文件中的文字是:

文本文件内容

如您所见,它仅将第一行的单词附加到列表中,但我希望将 txt 文件中的所有单词附加到列表中。

有谁知道我必须做什么? 这里有什么问题?

在返回列表之前,您应该将单词保存在主列表中。

def word_frequency(file): 

    with open(file) as f:
        lines = f.readlines()
        words = []
        for line in lines:
            line_words = line.split()
            words += line_words

        return words

在您的代码中,您只保存并返回第一行, return终止函数的执行并返回一个值。 在您的情况下,这只是文件的第一行。

一个答案来自https://www.pythonforbeginners.com/lists/count-the-frequency-of-elements-in-a-list#:~:text=Count%20frequency%20of%20elements%20in%20a%20list %20 使用,%20 频率%20of%20the%20element%20in%20the%20list

import collections

with open(file) as f:
       
    lines = f.readlines()
        
    words = []
        
    for line in lines:
        word = line.split(' ')
        words.append(word)

frequencyDict = collections.Counter(words)
print("Input list is:", words)
print("Frequency of elements is:")
print(frequencyDict)

您需要添加另一个 for 循环来计算行数

for line in file:
   for word in line.split(' ') :
      l = word

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM