繁体   English   中英

如何多次替换两个分隔符/字符串之间的唯一字符串

[英]How to replace unique string between two separators/strings multiple times

我正在浏览文件夹/目录并读取所有文件,检查是否有特定标签,然后仅在特定字符串在两个特定字符串/标签之间时才多次替换特定字符串。 这是文本文件的示例:

START $YES
N1 000 001 002
N2 TAG#1 004 008
N3 This is an apple
N4 006 005 003
(( TAG#2 ))
N5 This is an apple

我想要一个可以打开文件,检查START $YESSTART $NO并替换字符串的解决方案, This is an apple进入TAG#1TAG#2之间There is no apple ,仅当存在START $YES 我希望原始文件不受影响(使用fileinput库创建新文件或创建备份)。

目前,我无法发布python代码,但是当我回到办公桌时,将使用尝试的代码来更新此帖子。

import shutil

def func(srcname, dstname):
    replace = False
    with open(srcname) as srcfile:
        with open(dstname, 'w+') as dstfile:
            line = srcfile.readline().strip()
            if "START $NO" in line:
                srcfile.seek(0)
                shutil.copyfileobj(srcfile, dstfile)
                return
            while line:
                if "TAG" in line and not replace:
                    replace = True
                if "TAG" in line and replace:
                    replace = False
                if replace and "This is an apple" in line:
                    line = line.replace("This is an apple", "There is no apple")
                dstfile.write(line)
                line = srcfile.readline().strip()

暂无
暂无

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

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