我正在尝试让我的程序打印出在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))
并且两种方法最终都会吐出文本文件的每一行。有任何想法吗?感谢大家的帮助到目前为止。
答案 0 :(得分:0)
您正在使用等效标记(==)来设置printline变量。
它应该是" printline = False"设置," printline == False"比较
试试这个:
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变量的需求。
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) # This should only trigger if your if search.casefold() is in the line.casefold()
print("{} occurence(s) of the search item was/were found".format(found))