python - 在查找和替换 Word 文档期间提高 win32com 的性能
问题描述
我正在尝试创建一个脚本来查找和替换 Word 文档中的多个单词,win32com 对此非常有效,但它非常慢,并且超过 10 个术语可能需要几分钟。该脚本需要大约 5 分钟才能完成,并且 word 文档中每个术语出现 1 次。
import win32com.client as win32
term_list = ['Item0', 'Item1', 'Item2', 'Item3', 'Item4', 'Item4', 'Item5', 'Item6', 'Item7', 'Item8', 'Item9']
path_docx = r'C:\Temp\Document.docx'
word = win32.gencache.EnsureDispatch('Word.Application')
const = win32.constants
word.Visible = True
doc = word.Documents.Open(path_docx)
for paragraph in doc.Paragraphs:
#print(paragraph)
for item in term_list:
paragraph.Range.Find.Execute(FindText=item, ReplaceWith="Replaced", Replace=const.wdReplaceAll)
doc.SaveAs(r'C:\Temp\Document_replaced.docx')
我能做些什么来改进我的代码吗?
我也知道 python-docx 存在,但如果可能的话,我更喜欢使用 Word 本身来查找和替换。
编辑:
正如@tst 建议的那样,设置 word.Visible = False 有点帮助,但我的代码也对 COM 进行了多次调用,这降低了性能。这个新代码真的很快。它也可以很好地扩展,我可以在 5 秒内循环浏览大约 500 个术语的列表。
import win32com.client as win32
term_list = ['Item0', 'Item1', 'Item2', 'Item3', 'Item4', 'Item4', 'Item5', 'Item6', 'Item7', 'Item8', 'Item9']
path_docx = r'C:\Temp\Document.docx'
word = win32.gencache.EnsureDispatch('Word.Application')
const = win32.constants
word.Visible = False
doc = word.Documents.Open(path_docx)
for items in term_list:
findObject = word.Selection.Find
findObject.ClearFormatting()
findObject.Text = items
findObject.Replacement.ClearFormatting()
findObject.Replacement.Text = "FOUND"
findObject.Execute(Replace=win32.constants.wdReplaceAll)
doc.Save()
doc.Close()
解决方案
推荐阅读
- kubernetes - 由于 PSP(pod 安全策略)而导致 node-exporter 出现问题
- java - CDI @Produces Javadoc 需求说明
- android - 领域获得匹配查询的某些属性而不是所有属性?
- flutter - 有没有办法在 Flutter 中实现 Google Places 自动完成功能?
- javascript - 运行站点时端口 80 和 5500 之间的不同错误
- algorithm - 从列表中查找不正确的对象以保存网络请求
- android - Gradle 同步错误:重复键 AdditionalClassifierArtifactsImpl
- docker - docker 容器是否有私有或共享的本地驱动器(C:\、D:\)?
- asp.net - 如何路由 IdentityUser 的值(如用户名)而不是整个对象?
- html - 当我更改我的 Css 时,它在 Html 文件中不可见