python实现指定文档中指定字符串的替换-可循环替换多个字符串


随便写的一个简单小脚本,对字符串的完整匹配替换,后续也许有更多补充,随缘吧。。。废话不多说,直接贴代码:

 

#!/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
# TODO:输入需要替换的文档路径及名称
dirfile=input('请输入您需要替换字符的文档绝对路径:')
with open(dirfile,'r') as tfile:
    openfile=tfile.read()
# TODO:输入要替换的字符:
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('请输入正确指令!')


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM