[英]python print line if contains word
So im trying to let python search through my DataBase and then return the sentance where x is in This is my code so far所以我试图让 python 搜索我的数据库,然后返回 x 所在的句子这是我到目前为止的代码
word = input("")
x = open("Database.txt")
for line in x:
if (word) in line:
print(line)
else:
print("This start could not be found, maybe a typo, or try a different start!")
The error that i am getting when i type in a word that is in the DataBase.txt then it gives this当我输入 DataBase.txt 中的单词时出现的错误然后它给出了这个
Traceback (most recent call last):
File "DataSearcher_DataBase2.py", line 1, in <module>
word = input("")
File "<string>", line 1, in <module>
NameError: name 'BrokenRunes' is not defined
And when i type in a word that is not in the DataBase.txt then it gives me this what i told it to do with the else: code but then for every line that its not detected in so i would like that to only happen once当我输入一个不在 DataBase.txt 中的单词时,它会给我这个我告诉它与 else 做的事情:代码但是对于每一行它没有被检测到,所以我希望这种情况只发生一次
You want display the "not found" message only one time, so you need print it out of the for
您只想显示一次“未找到”消息,因此您需要将其for
出来
There are a few minor corrections too也有一些小的更正
word = input("")
found = False
x = open("Database.txt")
for line in x.readlines():
if word in line:
print(line)
found = True
if not found:
print("This start could not be found, maybe a typo, or try a different start!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.