[英]python print line if contains word
所以我試圖讓 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!")
當我輸入 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
當我輸入一個不在 DataBase.txt 中的單詞時,它會給我這個我告訴它與 else 做的事情:代碼但是對於每一行它沒有被檢測到,所以我希望這種情況只發生一次
您只想顯示一次“未找到”消息,因此您需要將其for
出來
也有一些小的更正
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.