繁体   English   中英

python 如果包含字则打印行

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM