【问题标题】:python print line if contains wordpython打印行是否包含单词
【发布时间】:2021-12-29 17:55:14
【问题描述】:

所以我试图让 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 做的事情:代码,但是对于没有检测到的每一行,我希望这样只发生一次

【问题讨论】:

  • 你在使用 Python 2 吗?
  • 我使用的是python版本Python 3.8.0

标签: python database search error-handling


【解决方案1】:

您只想显示一次“未找到”消息,因此您需要将其打印出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!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2016-04-07
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多