您的位置:首页 > 编程语言 > Python开发

python 批量修改预定字符串并将修改后的字符串插入文件指定位置

2017-03-07 10:52 411 查看
下面的例子是在文件的指定位置增加指定字符串的例子

修改配置文件:

def add_str(pre_str):  lines = []
flag = True
f = open("z.txt")
for line in f:
lines.append(line)
if line.strip("\n ") == "</se.diabol.jenkins.pipeline.DeliveryPipelineView>" and flag:
lines.append(pre_str)
flag = False
f.close()

f = open("z.txt", "w")
f.write("".join(lines))
f.close()


对预定的字符串批量替换指定字符:

import re
def multi_repalce(text, adict):
rx = re.compile('|'.join(map(re.escape, adict)))
#   def translate(match):
#     return adict[match.group(0)]
translate = lambda (match) : adict[match.group(0)]
return rx.sub(translate, text)


最后一段代码看了好长时间才稍微明白点。

map函数的第一个参数是一个function,第二个是一个序列,对这个序列的每一个元素都调用一遍这个函数返回之后的序列。下面两者是等价的。

map(re.escape, adict) == map(re.escape, adict.keys())


将上面生成的序列用 ‘|’ 分割开,作用是生成一个字符串的正则表达式,这个正则表达式匹配adict中的所有key

'|'.join(map(re.escape, adict))


re.compile()是将这个正则表达式进行翻译成真正的正则表达式。

re.compile('|'.join(map(re.escape, adict)))

print re.compile('|'.join(map(re.escape, adict))) #<_sre.SRE_Pattern object at 0x7f06779f5f30>
print type(re.compile('|'.join(map(re.escape, adict)))) #<type '_sre.SRE_Pattern'>

在text中找到匹配的rx,将匹配到的部分传递给translate函数。
re.sub的用法re.sub(pattern, repl, string, count=0, flags=0),pattern.compile.sub这里的pattern就是re.sub的第一个参数。

rx.sub(translate, text)


将匹配到的参数传递给tranlate函数后,match.group(0)就是匹配的第一个组,这里传的是匹配部分返回的肯定就是匹配到的key,最终返回字典key对应的value。在外层sub方法中进行替换。

translate = lambda (match) : adict[match.group(0)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: