没有合适的资源?快使用搜索试试~ 我知道了~
python实现替换word中的关键文字(使用通配符)
5星 · 超过95%的资源 6 下载量 193 浏览量
2020-12-20
17:58:40
上传
评论
收藏 49KB PDF 举报
温馨提示
试读
2页
环境: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.xlAp
资源详情
资源评论
资源推荐
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('' + string)
def add_doc_start(self, string):
'''在文档开头添加内容'''
rangee = self.doc.Range(0, 0)
rangee.InsertBefore(string + '')
def insert_doc(self, insertPos, string):
'''在文档insertPos位置添加内容'''
rangee = self.doc.Range(0, insertPos)
if (insertPos == 0):
rangee.InsertAfter(string)
else:
rangee.InsertAfter('' + 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()
weixin_38651273
- 粉丝: 0
- 资源: 969
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论10