繁体   English   中英

在文件python中复制文本部分

[英]copy section of text in file python

我需要从下面的文本文件中提取值:

fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk

我需要提取的值是从开始到结束。

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            copy = True
        elif line.strip() == "End":
            copy = False
        elif copy:
            outfile.write(line)

我正在使用的上面的代码来自这个问题: 使用python提取文本文件中两个字符串之间的值

该代码将不包含字符串“ Start”和“ End”,仅包含它们内部的内容。 您将如何包括周边字符串?

@en_Knight几乎正确。 这是一个满足OP要求在输出中包含定界符的修复程序:

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            copy = True
        if copy:
            outfile.write(line)
        # move this AFTER the "if copy"
        if line.strip() == "End":
            copy = False

或仅在适用于以下情况的情况下包括write():

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            outfile.write(line) # add this
            copy = True
        elif line.strip() == "End":
            outfile.write(line) # add this
            copy = False
        elif copy:
            outfile.write(line)

更新 :要回答注释“仅在'开始'之后使用'结束'的第一次出现”中的问题,请将最后一个elif line.strip() == "End"更改为:

        elif line.strip() == "End" and copy:
            outfile.write(line) # add this
            copy = False

如果只有一个“开始”行但有多个“结束”行,则此方法有效……听起来很奇怪,但这是发问者所要求的。

elif ”的意思是 “仅在其他情况失败时才执行此操作”。 如果您来自类似C语言的不同语言, 则在语法上等效于“ else if ”。 没有它,失败应该注意包括“开始”和“结束”

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            copy = True
        if copy: # flipped to include end, as Dan H pointed out
            outfile.write(line)
        if line.strip() == "End":
            copy = False

RegExp方法:

import re

with open('input.txt') as f:
    data = f.read()

match = re.search(r'\n(Start\n.*?\nEnd)\n', data, re.M | re.S)
if match:
    with open('output.txt', 'w') as f:
        f.write(match.group(1))

暂无
暂无

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

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