[英]Python: Searching a file for a specific string and outputting the total string count
尝试在 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
感觉您的问题中可能缺少一些东西,但我会尽力让您到达您想去的地方...
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)
这可能就是你想要做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.