如何多次替换两个 separators/strings 之间的唯一字符串
How to replace unique string between two separators/strings multiple times
我正在遍历一个 folder/directory 并读取所有文件,检查是否有某个标记,然后仅当它位于两个特定 strings/tags 之间时才多次替换特定字符串。
以下是文本文件的示例:
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 $YES
或 START $NO
,并将 [=16] 之间的字符串 This is an apple
替换为 There is no apple
=] 和 TAG#2
仅当存在 START $YES
时。我希望原始文件不受影响(创建新文件或使用 fileinput
库创建备份)。
我目前无法 post 我的 python 代码,但我会在回到办公桌后使用我尝试过的代码更新此 post。
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()
我正在遍历一个 folder/directory 并读取所有文件,检查是否有某个标记,然后仅当它位于两个特定 strings/tags 之间时才多次替换特定字符串。 以下是文本文件的示例:
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 $YES
或 START $NO
,并将 [=16] 之间的字符串 This is an apple
替换为 There is no apple
=] 和 TAG#2
仅当存在 START $YES
时。我希望原始文件不受影响(创建新文件或使用 fileinput
库创建备份)。
我目前无法 post 我的 python 代码,但我会在回到办公桌后使用我尝试过的代码更新此 post。
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()