替换文件中的多个字符串

las*_*pal 2 python

我试图替换文件中的多个字符串.

fp1 = open(final,"w")
data = open(initial).read()
for key, value in mydict.items():
    fp1.write(re.sub(key,value, data)
fp1.close()
Run Code Online (Sandbox Code Playgroud)

但只有我的最后一个键值被替换.如何替换文件中的所有键值.有没有更好的方法来替换文件中的多个字符串.

谢谢

`

Ale*_*lli 5

这是正则表达式可以真正帮助的一项任务:

import re

def replacemany(adict, astring):
  pat = '|'.join(re.escape(s) for s in adict)
  there = re.compile(pat)
  def onerepl(mo): return adict[mo.group()]
  return there.sub(onerepl, astring)

if __name__ == '__main__':
  d = {'k1': 'zap', 'k2': 'flup'}
  print replacemany(d, 'a k1, a k2 and one more k1')
Run Code Online (Sandbox Code Playgroud)

作为主脚本运行,a zap, a flup and one more zap根据需要打印.

这当然集中在字符串而不是文件上 - 替换本身就是在字符串到字符串的转换中发生的.基于RE的方法的优点是减少了循环:由于正则表达式引擎,所有要替换的字符串在一次传递中匹配.的re.escape呼叫确保含有特殊字符的字符串在RE模式语言被视为只是作为文字(无怪异含义;-),竖条表示"或",而sub方法调用嵌套onerepl对于每个匹配函数,将匹配对象因此,.group()调用可以轻松检索刚刚匹配且需要替换的特定字符串.

要在文件级别工作,

with open(final, 'w') as fin:
  with open(initial, 'r') as ini:
    fin.write(replacemany(mydict, ini.read()))
Run Code Online (Sandbox Code Playgroud)

with建议使用该声明,以确保正确关闭文件; 如果您遇到Python 2.5,请from __future__ import with_statement在模块或脚本的开头使用该with语句.