使用Python在多个文件中替换多个字符串
我有一个需要替换的文件列表和字符串列表,这些文件和字符串捕获在yaml文件中。我想编写一个函数来接受这个yaml文件并执行搜索和替换方法。这是我到目前为止得到的 2个文本文件和yaml文件 txt_1.txt使用Python在多个文件中替换多个字符串,python,regex,yaml,substitution,Python,Regex,Yaml,Substitution,我有一个需要替换的文件列表和字符串列表,这些文件和字符串捕获在yaml文件中。我想编写一个函数来接受这个yaml文件并执行搜索和替换方法。这是我到目前为止得到的 2个文本文件和yaml文件 txt_1.txt aB123.Abc AB345.aBC ab123.ABC Ab345.abc txt_2.txt ab123.Abc AB345.ABC current_date yaml_文件-cf_master.yml input_files: - txt_1.txt - txt
aB123.Abc
AB345.aBC
ab123.ABC
Ab345.abc
txt_2.txt
ab123.Abc
AB345.ABC
current_date
yaml_文件-cf_master.yml
input_files:
- txt_1.txt
- txt_2.txt
replacement_strings:
string1:
from: AB123.ABC
to: XY000.XYZ
string2:
from: AB345.ABC
to: XY001.ZYX
string3:
from: current_date
to: '2018-04-07'
目的是替换所有字符串(从值到值),忽略大小写(不区分大小写)
我不明白如何更正此代码。输入文件、yaml文件和生成的新文件都在同一个文件夹中您可以简化您的
yaml
文件。替换字符串不需要索引
input_files:
- txt_1.txt
- txt_2.txt
replacement_strings:
- from: AB123.ABC
to: XY000.XYZ
- from: AB345.ABC
to: XY001.ZYX
- from: current_date
to: '2018-04-07'
至于更换,您可能希望在两次过程中进行更换,首先使用临时标记进行更换,然后返回并使用实际更换来更换标记。这会阻止替换项彼此交互。例如,将所有'a'
替换为'b'
,将所有'b'
替换为'c'
。在没有中间标记步骤的情况下,第二次替换将替换所有原始的'b'
,但也将替换被替换的'a'
中的所有'b'
import yaml
import re
with open('cf_master.yml') as f:
data = yaml.safe_load(f)
for filepath in data['input_files']:
with open(filepath, 'r') as f:
txt = f.read()
marker_d = dict()
for i, d in enumerate(data['replacement_strings']):
marker = '__$TEMP{}$__'.format(i)
marker_d[marker] = d['to']
txt = re.sub(re.escape(d['from']), marker, txt, flags=re.I)
for marker, s in marker_d.items():
txt = re.sub(re.escape(marker), s, txt)
# Save file somewhere?
'更正此代码“-您一开始从未告诉我们您的代码有什么问题。请将您收到的错误消息文本添加到您的问题Hi Brendan,感谢两步技巧。我将记住这一点,因为它有助于验证输出。我添加了一些跟踪代码以将输出路由到另一个文件。输出文件基本上是以字符串“output”和顺序为前缀的输入文件名(例如:output\u 1\u input\u 1.txt)。其目的是为了验证目的而保留输入。你能帮我解决如何将输出路由到不同的文件吗?谢谢,帕里
import yaml
import re
with open('cf_master.yml') as f:
data = yaml.safe_load(f)
for filepath in data['input_files']:
with open(filepath, 'r') as f:
txt = f.read()
marker_d = dict()
for i, d in enumerate(data['replacement_strings']):
marker = '__$TEMP{}$__'.format(i)
marker_d[marker] = d['to']
txt = re.sub(re.escape(d['from']), marker, txt, flags=re.I)
for marker, s in marker_d.items():
txt = re.sub(re.escape(marker), s, txt)
# Save file somewhere?