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


    下面的例子是在文件的指定位置增加指定字符串的例子

    修改配置文件:

    def add_str(pre_str):  lines = []
      flag = True
      f = open("z.txt")
      for line in f:
        lines.append(line)
        if line.strip("
     ") == "</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(patternreplstringcount=0flags=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)]
  • 相关阅读:
    Pausing Coyote HTTP/1.1 on http-8080
    网站后台管理中生成首页失败
    Eclipse快捷键集结
    电子商务网站推广10大方法
    Eclipse使用
    注册表中更换桌面背景
    网站卡死,照惯例运行.bat批量处理文件进行重启不起作用
    同时处理html+js+jquery+css的插件安装(Spket&Aptana插件安装)
    JQuery的插件
    Eclipse插件
  • 原文地址:https://www.cnblogs.com/badboyf/p/6513560.html
Copyright © 2020-2023  润新知