如何让这两个Python脚本一起工作?

时间:2017-11-01 18:22:16

标签: python text full-text-search phrase

  • (1)下面是我编写的用于查看文件,找到我的搜索的代码 短语和复制该行。



with open("C:\Python34\Python Code\Output.txt") as infile:
        with open("C:\Python34\Python Code\Input.txt", "w") as outfile:
            for line in infile:
                if "This Phrase:" in line:
                    outfile.write(line)




  • (2)下面是我编写的第二部分代码,用于搜索文件中的"开始短语"和"结束短语",并将其间的所有行复制到新文件中。这也有效。

但我似乎无法将它们结合在一起工作!当我尝试时,我尝试的各种方式都会出现错误。 Python初学者。

在我试图搜索的文件中,上面的代码(1)需要执行其操作,然后代码(2)需要按照该顺序执行其操作。

with open("C:\Python34\Python Code\Output.txt") as infile, open("C:\Python34\Python Code\Input.txt", "w") as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start-Prase":
            copy = True
        elif line.strip() == "End-Phrase":
            copy = False
        elif copy:
            outfile.write(line)

1 个答案:

答案 0 :(得分:0)

您是否正在寻找以下内容:

with open("C:\Python34\Python Code\Output.txt") as infile, open("C:\Python34\Python Code\Input.txt", "w") as outfile:
copy = False
for line in infile:
    if line.strip() == "Start-Phrase":
        copy = True
    elif line.strip() == "End-Phrase":
        copy = False
    elif copy:
        if "This Phrase:" in line:
                outfile.write(line)

我不确定你是想写出每一行还是只写一些行。您还可能需要将行(文本)分开,具体取决于它们的格式。