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