天天看點

python替換word中的關鍵文字(使用通配符)

  環境: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, False, False, False, False, True, 1, True, new_string, 2)

    def replace_docs(self, string, new_string):
        '''采用通配符比對替換'''
        self.xlApp.Selection.Find.ClearFormatting()
        self.xlApp.Selection.Find.Replacement.ClearFormatting()
        self.xlApp.Selection.Find.Execute(string, False, False, True, False, False, False, 1, False, new_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()
           

參考:https://www.cnblogs.com/zhuluqing/p/8445901.html

https://blog.csdn.net/baidu_39416074/article/details/80926443