可以把要替换的内容写成一个替换对照的列表,然后循环列表多次执行re.sub()进行替换
import re
f=open('/home/wuzz/11.txt','r')
alllines=f.readlines()
f.close()
f=open('/home/wuzz/11.txt','w+')
plist = [
('hello','hi'),
('12345','21356'),
('yuhg','ksus'),
]
for eachline in alllines:
for reg,text in plist:
eachline = re.sub(reg,text,eachline)
f.writelines(eachline)
f.close()
或者不用循环,直接多写几个re.sub()也可以
import re
f=open('/home/wuzz/11.txt','r')
alllines=f.readlines()
f.close()
f=open('/home/wuzz/11.txt','w+')
for eachline in alllines:
a=re.sub('hello','hi',eachline)
a=re.sub('12345','21356',a)
a=re.sub('yuhg','ksus',a)
f.writelines(a)
f.close()