【问题标题】:Can I use Win32 COM to replace text inside a word document?我可以使用 Win32 COM 替换 word 文档中的文本吗?
【发布时间】:2010-11-05 22:45:11
【问题描述】:

我必须在某些文档中执行大量替换,问题是,我希望能够自动执行该任务。一些文档包含常见的字符串,如果可以自动化,这将非常有用。从我目前阅读的内容来看,COM 可能是这样做的一种方式,但我不知道是否支持文本替换。 我希望能够在 python 中执行此任务?可能吗?您能否发布一个代码 sn-p 显示如何访问文档的文本?

谢谢!

【问题讨论】:

    标签: python winapi com ms-word replace


    【解决方案1】:

    查看此链接:http://python.net/crew/pirx/spam7/

    左侧的链接指向文档。

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

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

    【讨论】:

      【解决方案2】:

      如果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。

      【讨论】:

        【解决方案3】:

        看看this 是否让你开始使用 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
        

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

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

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

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

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

        (VB)

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

        Python

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

        请原谅我的 Python 知识。但是,我希望您有前进的想法。
        完成查找/替换操作后,记得在文档上保存并关闭。

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

        【讨论】:

        • 伯尼的回答包括实际完整的 python 代码。这个答案可能更简洁,包括更完整的python。
        • 如何使用win32高亮word文档中的文字?
        【解决方案4】:

        到目前为止,我喜欢这些答案;
        这是一个经过测试的示例(从 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')
        

        【讨论】:

        • 我喜欢这有一个完整的例子。
        • 如何使用win32高亮word文档中的文字?
        【解决方案5】:

        您也可以使用 VBScript 实现此目的。只需将代码输入到名为script.vbs 的文件中,然后打开命令提示符(开始-> 运行-> 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
        
        

        【讨论】:

        • OP 特别询问了 python。
        猜你喜欢
        • 2013-08-21
        • 1970-01-01
        • 2019-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-24
        • 1970-01-01
        相关资源
        最近更新 更多