Skip to main content
 首页 » 编程设计

Python:在文件中搜索特定字符串并输出字符串总数

2025年04月02日25powertoolsteam

尝试在 python 中构建搜索功能,从用户那里获取输入值/字符串,搜索外部文件,然后返回文件中该请求值的总数(总和)。

if user_search_method == 1: 
with open("file.txt", 'r') as searchfile: 
    for word in searchfile: 
        word = word.lower() 
        total = 0 
        if user_search_value in word.split(): 
            total += word.count(user_search_value) 
            print total 

当我运行它时,我得到的是逐行显示的计数而不是总和。当我将这些行加起来时,它们也总是比实际少 1 个计数。

请您参考如下方法:

您要在每次迭代中打印total,您必须将它放在for 循环之外。您也可以使用一个生成器表达式来更 Pythonic 地完成这项工作:

if user_search_method == 1: 
    with open("file.txt") as searchfile: 
        total = sum(line.lower().split().count(user_search_value) for line in searchfile) 
    print total