gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:01 24 4
gpt4 key购买 nike

尝试在 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

关于Python:在文件中搜索特定字符串并输出字符串总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39428907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com