首页 > 解决方案 > 在查找和替换 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()

标签: pythonpython-3.xwin32com

解决方案


推荐阅读