使用python计算文本文件中单词的出现次数

时间:2018-01-26 01:14:49

标签: python full-text-search

我复制了教程中的代码来计算文本文件中单词的出现次数,但由于某种原因,程序错误计数(似乎最多为6)。我使用来自不同文件的文本测试了它但由于某种原因它没有正确计数。

这是我的代码:

search = input("Input your search term: ") 
found = 0

with open ("search.txt", 'r') as data:
    for line in data: 
        if search.casefold() in line.casefold():  
            found += 1

    print(found)

我的代码有问题吗?

1 个答案:

答案 0 :(得分:1)

如果您将代码更改为:

search = input("Input your search term: ")  
found = 0

with open ("search.txt", 'r') as data:
    for line in data: 
        if search.casefold() in line.casefold():  
            found += line.casefold().count(search.casefold())

    print(found)

这会有所作为吗?如果单词在一行中出现多次,则代码只计算一次。