Skip to main content
 首页 » 编程设计

python之如何计算一个词在文本中出现的次数

2024年10月25日10hnrainll

我是 python 的新手,我不知道如何解决这个问题:编写一个函数来计算一个单词在文本中出现的次数。到目前为止,这是我的代码,但我被卡住了。我想我需要找到一种方法来将文本拆分为单词,但它在列表中,所以我不能这样做。

def searcher(file): 
    f = open(file,"r") 
    word = raw_input("Write your word: ") 
    text = f.readlines() 
    text1 = text.split() 
    counter = 0 
    for x in text1: 
        if x == word: 
            counter = counter +1 
    print counter 

提前致谢

请您参考如下方法:

使用collections.Counter在每一行 split 中传递单个单词。

s = "foo foo foobar bar" 
from collections import Counter 
print Counter(s.split()) 
Counter({'foo': 2, 'foobar': 1, 'bar': 1}) 
 
def searcher(file): 
    c = Counter() 
    word = raw_input("Write your word: ") 
    with open(file,"r") as f: 
       for line in f: 
           c.update(line.lower().rstrip().split()) 
    return c.get(word)