首页 > 解决方案 > 如何替换不同文件中动态的一段文本?

问题描述

这是我的 Python 代码:

with open('input.txt', 'r') as file:
filedata = file.read()

filedata = filedata.replace("""section a {
sub1{ Dynamic Content 1}   
sub2{ Dynamic Content 2}      
sub3{ Dynamic Content 3}

 };""", """section a {
 sub1{ Dynamic Content 1}   
 sub2{ This is replacement text }     
 sub3{ Dynamic Content 3} 
 };""")

with open('input.txt', 'w') as file:
file.write(filedata)

input.txt 文件:

section a {
sub1{ Dynamic Content 1}  
sub2{ Dynamic Content 2}      
sub3{ Dynamic Content 3}

};


section b {
sub1{ Dynamic Content 4}   
sub2{ Dynamic Content 5}
sub3{ Dynamic Content 6}

};

我还有一些类似input.txt格式的文件。IE

  1. 节 a 和节 b 在给定文件中是唯一的、静态的和非重复的。
  2. sub1, sub2,sub3在给定文件中是静态且重复的。
  3. sub1, sub2,中的内容sub3因文件而异input.txt

"This is replacement text"无论动态内容如何,​​我都想替换 a-sub2 部分中的内容。

如果我知道动态内容,上面的脚本就可以工作。

标签: pythonstringdynamicreplace

解决方案


尝试:

import re

def replaceText():
    with open('input.txt') as file:
        filedata=file.read()
        newText=re.sub(r'(section a.*?sub2)({.*?})', r'\1{This is replacement text}', filedata, flags=re.DOTALL)
    with open('input.txt', 'w') as outfile:
        outfile.write(newText)

replaceText()

推荐阅读