问题:有若干 xml 文件,每个 xml 文件内有如下类似字段:
id=@a b c {e f g}
是要将{与}之间的所有的“空格”改为“_”?
notepad++中正则表达式做不到这个要求, 可以用python代码来做
你题目的解答代码如下:
import re
s = '''
id=@a b c {e f g}
id=@f g ht {it et g}
'''
s = re.sub(r'\{.*?\}',lambda x: re.sub(r' ',r'_',x.group(0)),s)
print(s)
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
import re
import os
text = '''
id=@a b c {e f g}
id=@f g ht {it et g}
'''
pattern = '\{(.+?)\}'
result_dir = './result'
if not os.path.exists(result_dir):
os.mkdir(result_dir)
for p, d, f in os.walk('.'):
for file in f:
if file.endswith('.xml'):
print(f'solving {file}...')
with open(os.path.join(p, file), 'r') as ori:
text = ori.read()
text = re.sub(pattern, lambda x: re.sub(
' ', '_', x.group(0)), text)
with open(os.path.join(result_dir, file), 'w+') as output:
output.write(text)
放在待处理的文件夹内运行,会在该目录下生成一个result文件夹,里面是批量处理后的结果
有帮助望采纳~
notepad CTRL+F替换,查找模式选择正则
查找目标:\b\s+\b(?=\S[^{]*})
替换为:_
全部替换