简体   繁体   English

python 如果包含字则打印行

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

相关问题 在python中按行搜索和打印单词 - Search and print word in line in python 打印包含“word”python的行 - Print line containing “word” python Python-如果字母中包含“好”字和“坏”字,请打印出来 - Python - If a “good” word and a “bad” word contains in a letter, print it out python-打印包含正则表达式匹配项的行和列表 - python - print line and list that contains regex match 在同一行 Python 上打印同一个单词 3 次 - Print the same word 3 times on the same line Python 搜索文件中的单词并打印python中出现该单词的行号 - search a word in a file and print the line number where that word occurs in python PYTHON如何检查某行是否包含特定字母,以及是否不打印该行 - PYTHON How to check if a line contains specific letters and if not print the line 如何创建一个包含文件中每一行的第一个单词的列表(Python 3) - How to create a list that contains the first word of every line in a file (Python 3) 如何为字典中的新行打印 1 个值,其中包含 python 中的 2 个值? - How to print 1 value for a new line from dictionary contains 2 values in python? 如何在文本文件中查找一个单词并打印 Python 下一行中的另一个单词 - How to find a word in a text file and print another that is in the next line in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM