[英]Python: Searching a file for a specific string and outputting the total string count
Attempting to build a search functionality in python that takes an input value/string from the user, searches an external file, and then returns the total count (sum) of that requested value in the file.尝试在 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
When I run this though I get a line-by-line count displayed and not a total sum.当我运行它时,虽然我得到了一行一行的显示而不是总和。 When I add up those lines they are always 1 count short of the actual too.
当我把这些行加起来时,它们也总是比实际少 1 个计数。
You are printing the total
in each iteration, you have to put it out of for
loop.您在每次迭代中打印
total
,您必须将其置于for
循环之外。 Also you can do this job more pythonic, using one generator expression:你也可以使用一个生成器表达式来做更多的 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
It feels like there might be something missing from your question, but I will try to get you to where it seems you want to go...感觉您的问题中可能缺少一些东西,但我会尽力让您到达您想去的地方...
user_search_value = 'test' # adding this for completeness of
# this example
if user_search_method == 1:
with open("file.txt", 'r') as searchfile:
total = 0
for word in searchfile:
words = word.lower().split() # breaking the words out, upfront, seems
# more efficient
if user_search_value in words:
total += words.count(user_search_value)
print total # the print total statement should be outside the for loop
if user_search_method == 1:
total = 0
with open('file.txt') as f:
for line in f:
total += line.casefold().split().count(user_search_value.casefold())
print(total)
This is probably what you wanted doing.这可能就是你想要做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.