随便写的一个简单小脚本,对字符串的完整匹配替换,后续也许有更多补充,随缘吧。。。:
#!/usr/bin/env python3
# -*-coding: utf-8 -*-
# @Time:2019/12/10 14:22
# @User: wsn
# @Author: WSN
# @File: str_replace.py
import re,sys,os
# 输入需要替换的文档路径及名称
dirfile=input('请输入您需要替换字符的文档绝对路径:')
with open(dirfile,'r') as tfile:
openfile=tfile.read()
# 输入要替换的字符:
while True:
kw = input('是否需要替换字符:') #1:替换 0:退出
tw = kw.isdigit()
if tw:
if int(kw):
oldstr=input('输入原字符:')
nu=len(re.findall(oldstr,openfile))
newstr=input('替换字符为:')
print('原文档中共有%d个%s被替换成%s' % (nu, oldstr,newstr))
openfile=re.sub(oldstr,newstr,openfile)
else:
print(openfile)
newfile = list(os.path.split(dirfile))[0] + '/new-' + list(os.path.split(dirfile))[1]
with open(newfile, 'w') as new:
new.write(openfile)
sys.exit()
else:
print('请输入正确指令!')