简体   繁体   English

如何从包含特定短语的文本文件中打印每一行

[英]How to print every line from a text file that contains a certain phrase

I have to write a function which can search a txt file for a phrase then print every line that contains the phrase. 我必须编写一个函数,该函数可以在txt文件中搜索短语,然后打印包含该短语的每一行。

def find_phrase(filename,phrase):
    for line in open(filename):
        if phrase in line: 
            print line,

That is what I have at the moment and it only prints the first instance. 这就是我目前所拥有的,它只打印第一个实例。

I have tried your code with a sample script, which goes like this 我已经用示例脚本尝试了您的代码,就像这样

#sample.py

import sys
print "testing sample"
sys.exit() 

when i run your script, 当我运行您的脚本时,

find_phrase('sample.py','sys')

It prints, 它打印,

import sys
sys.exit(). 

If this is not your intended output, please share the file you are using. 如果这不是您想要的输出,请共享您正在使用的文件。

Below is the pythonic approach. 以下是pythonic方法。 The with statement will safely open the file and handle closing the file when it is done. with语句将安全地打开文件并在完成后处理关闭文件。 You can also open multiple files with the "with" statement. 您也可以使用“ with”语句打开多个文件。 How to open a file using the open with statement 如何使用open with语句打开文件

def print_found_lines(filename, phrase):
    """Print the lines in the file that contains the given phrase."""
    with open(filename, "r") as file:
        for line in file:
            if phrase in line:
                print(line.replace("\n", ""))
    # end with (closes file automatically)
# end print_found_lines

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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