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 ists(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 = ''python正则表达式爬虫
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对象
# 这⾥演⽰替换内容,其他功能⾃⼰按照上⾯类的功能按需使⽤
# place_docs('([0-9])@[、,,]([0-9])@', '\1.\2')  使⽤@不能识别改⽤{1,},\需要使⽤反斜杠转义
doc.close()
以上这篇python实现替换word中的关键⽂字(使⽤通配符)就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。