【问题标题】:How to print every line from a text file that contains a certain phrase如何从包含特定短语的文本文件中打印每一行
【发布时间】:2014-04-02 10:29:23
【问题描述】:

我必须编写一个函数,它可以在 txt 文件中搜索一个短语,然后打印包含该短语的每一行。

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

这就是我目前所拥有的,它只打印第一个实例。

【问题讨论】:

  • 这应该可以。您确定您有多个匹配(区分大小写)的行吗?另外:使用 with 语句,这样您就可以在完成后自动关闭文件。
  • 它对我来说适用于一个简单的示例文件。你能告诉我们你正在使用的文件吗?
  • 它也对我有用。您可以发布代码的输出示例吗?

标签: python string file-io


【解决方案1】:

我已经使用示例脚本尝试了您的代码,如下所示

#sample.py

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

当我运行你的脚本时,

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

打印出来,

import sys
sys.exit(). 

如果这不是您想要的输出,请分享您正在使用的文件。

【讨论】:

    【解决方案2】:

    下面是pythonic方法。 with 语句将安全地打开文件并在完成后处理关闭文件。您还可以使用“with”语句打开多个文件。 How to open a file using the open with statement

    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
    

    【讨论】:

    • 您应该用空格替换。为了重现原始发布的代码。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多