python - 如何替换不同文件中动态的一段文本?
问题描述
这是我的 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
- 节 a 和节 b 在给定文件中是唯一的、静态的和非重复的。
sub1
,sub2
,sub3
在给定文件中是静态且重复的。sub1
,sub2
,中的内容sub3
因文件而异input.txt
。
"This is replacement text"
无论动态内容如何,我都想替换 a-sub2 部分中的内容。
如果我知道动态内容,上面的脚本就可以工作。
解决方案
尝试:
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()
推荐阅读
- python - 如何使用熊猫用相邻列的值替换
- google-bigquery - Bigquery比特币数据集SQL查询获取时间戳后的交易
- node.js - 猫鼬,nodejs,在子文档中按日期排序
- javascript - 重命名工作表时如何更新 Google Sheet Add-on 侧边栏下拉列表?
- typescript - 元素查找器的量角器扩展方法
- go - 无法将 websocket 数据从颤振应用程序发送到服务器
- c# - 如何让 Swagger 将模型模式枚举生成为字符串而不是 int?
- node.js - Babel 解析器没有为 sytax 错误显示正确的文件名
- java - 在 JAVA 上与 TelegramBOT 进行对话
- r - 仅选择列名与其他 df 中的行中的值匹配的列