尝试在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个。
答案 0 :(得分:2)
您在每次迭代中打印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
答案 1 :(得分:0)
感觉你的问题可能会遗漏一些东西,但我会尝试让你到达你想去的地方......
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
答案 2 :(得分:-1)
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)
这可能就是你想做的事。