我可以使用Win32 COM替换word文档中的文本吗?

Geo*_*Geo 4 python com winapi replace ms-word

我必须在一些文档中执行大量替换,事情是,我希望能够自动执行该任务.一些文档包含公共字符串,如果它可以自动化,这将非常有用.从我到目前为止所读到的,COM可能是这样做的一种方式,但我不知道是否支持文本替换.我希望能够在python中执行此任务?可能吗?你可以发一个代码片段来展示如何访问文档的文本吗?

谢谢!

ber*_*nie 10

我喜欢到目前为止的答案;
这是一个经过测试的示例(稍微修改一下)
,它替换了Word文档中出现的所有字符串:

import win32com.client

def search_replace_all(word_file, find_str, replace_str):
    ''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''
    wdFindContinue = 1
    wdReplaceAll = 2

    # Dispatch() attempts to do a GetObject() before creating a new one.
    # DispatchEx() just creates a new one. 
    app = win32com.client.DispatchEx("Word.Application")
    app.Visible = 0
    app.DisplayAlerts = 0
    app.Documents.Open(word_file)

    # expression.Execute(FindText, MatchCase, MatchWholeWord,
    #   MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, 
    #   Wrap, Format, ReplaceWith, Replace)
    app.Selection.Find.Execute(find_str, False, False, False, False, False, \
        True, wdFindContinue, False, replace_str, wdReplaceAll)
    app.ActiveDocument.Close(SaveChanges=True)
    app.Quit()

f = 'c:/path/to/my/word.doc'
search_replace_all(f, 'string_to_be_replaced', 'replacement_str')
Run Code Online (Sandbox Code Playgroud)


sha*_*esh 8

看看这是否为您提供了使用python进行文字自动化的开始.

打开文档后,您可以执行以下操作.
在以下代码之后,您可以关闭文档并打开另一个.

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "test"
    .Replacement.Text = "test2"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Run Code Online (Sandbox Code Playgroud)

上面的代码将文本"test"替换为"test2"并执行"replace all".
您可以根据需要将其他选项设置为true/false.

学习这个的简单方法是创建一个包含您想要执行的操作的宏,查看生成的代码并在您自己的示例中使用它(使用/不使用修改的参数).

编辑:在看了Matthew的一些代码之后,你可以做以下几点

MSWord.Documents.Open(filename)
Selection = MSWord.Selection
Run Code Online (Sandbox Code Playgroud)

然后将上面的VB代码翻译成Python.
注意:以下VB代码是在不使用长语法的情况下分配属性的简便方法.

(VB)

With Selection.Find
    .Text = "test"
    .Replacement.Text = "test2"
End With
Run Code Online (Sandbox Code Playgroud)

蟒蛇

find = Selection.Find
find.Text = "test"
find.Replacement.Text = "test2"
Run Code Online (Sandbox Code Playgroud)

请原谅我的python知识.但是,我希望你能够继续前进.
完成查找/替换操作后,请记住在文档上执行保存并关闭.

最后,您可以调用MSWord.Quit(从内存中释放Word对象).