【发布时间】:2018-01-26 17:49:03
【问题描述】:
我正在尝试让我的程序打印 Python 中出现搜索项的行。这是我目前的尝试:
search = input("Input your search term: ")
found = 0
printline == False
with open ("search.txt", 'r') as data:
for line in data:
if search.casefold() in line.casefold():
found += line.casefold().count(search.casefold()) #adds the number of occurences within a line
printline == True
if printline == True:
print(line)
else:
printline == False
print("{} occurence(s) of the search item was/were found".format(found))
它一直说“打印线”未定义。我以为我在顶部定义了它。
更新:我将“printline”作为全局变量删除,并将其移至 for 循环的开头。现在代码打印每一行文本(不仅仅是包含搜索词的行)。这是我试图避免的,也是我想出“printline”变量开始的原因。
为了澄清,我试过了:
search = input("Input your search term: ")
found = 0
with open ("search.txt", 'r') as data:
for line in data:
if search.casefold() in line.casefold():
found += line.casefold().count(search.casefold()) #adds the number of occurences within a line
print(line)
print("{} occurence(s) of the search item was/were found".format(found))
我已经试过了:
search = input("Input your search term: ")
found = 0
with open ("search.txt", 'r') as data:
for line in data:
printline = False
if search.casefold() in line.casefold():
found += line.casefold().count(search.casefold()) #adds the number of occurences within a line
printline = True
if printline == True:
print(line)
else:
printline = False
print("{} occurence(s) of the search item was/were found".format(found))
这两种方法最终都会吐出文本文件的每一行。有任何想法吗?感谢大家到目前为止的帮助。
【问题讨论】:
-
=太多。做printline = False。
标签: python full-text-search keyword-search