python實現替換word中的關鍵文字(使用萬用字元)
阿新 • • 發佈:2020-02-14
環境:Python3.6
本文主要是通過win32com操作word,對word中進行常用的操作。本文以替換為例,講解一下如何使用Python在word中使用“萬用字元模式”(類似於正則表示式)替換文字內容。
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import win32com from win32com.client import Dispatch # 處理Word文件的類 class RemoteWord: def __init__(self,filename=None): self.xlApp = win32com.client.Dispatch('Word.Application') # 此處使用的是Dispatch,原文中使用的DispatchEx會報錯 self.xlApp.Visible = 0 # 後臺執行,不顯示 self.xlApp.DisplayAlerts = 0 #不警告 if filename: self.filename = filename if os.path.exists(self.filename): self.doc = self.xlApp.Documents.Open(filename) else: self.doc = self.xlApp.Documents.Add() # 建立新的文件 self.doc.SaveAs(filename) else: self.doc = self.xlApp.Documents.Add() self.filename = '' def add_doc_end(self,string): '''在文件末尾新增內容''' rangee = self.doc.Range() rangee.InsertAfter('\n' + string) def add_doc_start(self,string): '''在文件開頭新增內容''' rangee = self.doc.Range(0,0) rangee.InsertBefore(string + '\n') def insert_doc(self,insertPos,string): '''在文件insertPos位置新增內容''' rangee = self.doc.Range(0,insertPos) if (insertPos == 0): rangee.InsertAfter(string) else: rangee.InsertAfter('\n' + string) def replace_doc(self,string,new_string): '''替換文字''' self.xlApp.Selection.Find.ClearFormatting() self.xlApp.Selection.Find.Replacement.ClearFormatting() #(string--搜尋文字,# True--區分大小寫,# True--完全匹配的單詞,並非單詞中的部分(全字匹配),# True--使用萬用字元,# True--同音,# True--查詢單詞的各種形式,# True--向文件尾部搜尋,# 1,# True--帶格式的文字,# new_string--替換文字,# 2--替換個數(全部替換) self.xlApp.Selection.Find.Execute(string,False,True,1,new_string,2) def replace_docs(self,new_string): '''採用萬用字元匹配替換''' self.xlApp.Selection.Find.ClearFormatting() self.xlApp.Selection.Find.Replacement.ClearFormatting() self.xlApp.Selection.Find.Execute(string,2) def save(self): '''儲存文件''' self.doc.Save() def save_as(self,filename): '''文件另存為''' self.doc.SaveAs(filename) def close(self): '''儲存檔案、關閉檔案''' self.save() self.xlApp.Documents.Close() self.xlApp.Quit() if __name__ == '__main__': # path = 'E:\\XXX.docx' path = 'E:/XXX.docx' doc = RemoteWord(path) # 初始化一個doc物件 # 這裡演示替換內容,其他功能自己按照上面類的功能按需使用 doc.replace_doc(' ','') # 替換文字內容 doc.replace_doc('.','.') # 替換.為. doc.replace_doc('\n','') # 去除空行 doc.replace_doc('o','0') # 替換o為0 # doc.replace_docs('([0-9])@[、,,]([0-9])@','\1.\2') 使用@不能識別改用{1,},\需要使用反斜槓轉義 doc.replace_docs('([0-9]){1,}[、,,.]([0-9]){1,}','\\1.\\2') # 將數字中間的,,、.替換成. doc.replace_docs('([0-9]){1,}[舊]([0-9]){1,'\\101\\2') # 將數字中間的“舊”替換成“01” doc.close()
以上這篇python實現替換word中的關鍵文字(使用萬用字元)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。