代码之家  ›  专栏  ›  技术社区  ›  Geo

我可以使用win32 com替换Word文档中的文本吗?

  •  4
  • Geo  · 技术社区  · 16 年前

    我必须在一些文档中执行大量的替换操作,但问题是,我希望能够自动完成这项任务。一些文档包含公共字符串,如果可以自动化,这将非常有用。据我目前所知,COM可能是实现这一点的一种方法,但我不知道是否支持文本替换。 我想用python来执行这个任务?有可能吗?你能发布一个代码片段来展示如何访问文档的文本吗?

    谢谢!

    5 回复  |  直到 12 年前
        1
  •  8
  •   shahkalpesh    16 年前

    看看是否 this 让您从使用python的Word自动化开始。

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

    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
    

    上面的代码将文本“test”替换为“test2”,并执行“replace all”。
    您可以根据需要将其他选项设为“真/假”。

    了解这一点的简单方法是创建一个宏,其中包含您想要执行的操作,请参见生成的代码,并在您自己的示例中使用它(有/无修改的参数)。

    编辑:在看了Matthew的一些代码之后,您可以执行以下操作

    MSWord.Documents.Open(filename)
    Selection = MSWord.Selection
    

    然后把上面的vb代码翻译成python。
    注意:下面的VB代码是不使用长语法分配属性的简写方法。

    (VB)

    With Selection.Find
        .Text = "test"
        .Replacement.Text = "test2"
    End With
    

    蟒蛇

    find = Selection.Find
    find.Text = "test"
    find.Replacement.Text = "test2"
    

    请原谅我的巨蟒知识。但是,我希望你能有这个想法。
    完成查找/替换操作后,请记住对文档执行保存和关闭操作。

    最后,你可以打电话 MSWord.Quit (从内存中释放Word对象)。

        2
  •  10
  •   mechanical_meat nazca    12 年前

    我喜欢目前为止的答案;
    下面是一个经过测试的示例(稍微修改了 here )
    替换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')
    
        3
  •  3
  •   Matthew Flaschen    16 年前

    如果 this mailing list post 是的,访问文档的文本很简单,如下所示:

    MSWord = win32com.client.Dispatch("Word.Application")
    MSWord.Visible = 0 
    MSWord.Documents.Open(filename)
    docText = MSWord.Documents[0].Content
    

    也看到 How to: Search for and Replace Text in Documents . 示例使用了vb和c,但基础知识也应该应用于python。

        4
  •  2
  •   Christopher    16 年前

    签出此链接: http://python.net/crew/pirx/spam7/

    左侧的链接指向文档。

    您可以使用对象模型来概括这一点,在这里可以找到:

    http://msdn.microsoft.com/en-us/library/kw65a0we(VS.80).aspx

        5
  •  2
  •   Ra.    16 年前

    您也可以使用 VBScript . 只需将代码键入名为 script.vbs ,然后打开命令提示符(start->run->cmd),然后切换到脚本所在的文件夹并键入:

    cscript script.vbs 
    
    strFolder = "C:\Files"
    
    Const wdFormatDocument  = 0
    
    'Select all files in strFolder
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colFiles = objWMIService.ExecQuery _
        ("ASSOCIATORS OF {Win32_Directory.Name='" & strFolder & "'} Where " _
            & "ResultClass = CIM_DataFile")
    
    'Start MS Word
    Set objWord = CreateObject("Word.Application")
    
    Const wdReplaceAll = 2
    Const wdOrientLandscape = 1
    
    
    For Each objFile in colFiles
        If objFile.Extension = "doc" Then
            strFile = strFolder & "\" & objFile.FileName & "." & objFile.Extension
            strNewFile = strFolder & "\" & objFile.FileName & ".doc"
            Wscript.Echo "Processing " & objFile.Name & "..."
    
            Set objDoc = objWord.Documents.Open(strFile)
    
            objDoc.PageSetup.Orientation = wdOrientLandscape
    
            'Replace text - ^p in a string stands for new paragraph; ^m stands for page break
            Set objSelection = objWord.Selection
            objSelection.Find.Text = "String to replace"
            objSelection.Find.Forward = TRUE
            objSelection.Find.Replacement.Text = "New string"
    
            objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
    
            objDoc.SaveAs strNewFile, wdFormatDocument
            objDoc.Close
            Wscript.Echo "Ready"
        End If
    Next
    
    objWord.Quit