如何在文本文件中搜索单词并用 Python 打印整行?

Dav*_*dez 1 python printing python-3.x

我有正确的代码:

with open("text.txt") as openfile:
    for line in openfile:
        for part in line.split():
            if "Hello" in part:
                print(part)
Run Code Online (Sandbox Code Playgroud)

只能在文本中找到像 hello 这样的特定单词并打印它。问题是,我希望它停止仅打印该单词并打印包含该单词的整行。我怎样才能做到这一点?

这是我现在得到的结果:

hello
hello
hello
Run Code Online (Sandbox Code Playgroud)

然而,文本文件包括:

hello, i am a code
hello, i am a coder
hello, i am a virus
Run Code Online (Sandbox Code Playgroud)

Gus*_*ste 5

你只是做一个不必要的循环,试试这个:

with open("text.txt") as openfile:
    for line in openfile:
        if "Hello" in line:
            print(line)
Run Code Online (Sandbox Code Playgroud)