Python替换某个文本中的
字符串,然后生成新的文本文档,代码如下:import osos.chdir('D:\\') # 跳到D盘if not os.path.exists('test1.txt'): # 看一下这个
文件是否存在exit(-1) #不存在就退出lines = open('test1.txt').readlines() #打开文件,读入每一行fp = open(''test2.txt','w') #打开你要写得文件test2.txtfor s in lines:# replace是替换,write是写入fp.write( s.replace('love','hate').replace('yes','no'))fp.close() # 关闭文件
python中快速进行多个字符替换的方法小结
先给出结论:
要替换的字符数量不多时,可以直接链式replace()方法进行替换,效率非常高;
如果要替换的字符数量较多,则推荐在 for 循环中调用 replace() 进行替换。
可行的方法:
1. 链式replace()
?
1 string.replace().replace()
1.x 在for循环中调用replace() 「在要替换的字符较多时」
2. 使用string.maketrans
3. 先 re.compile 然后 re.sub