Docx比较和编辑?

时间:2018-01-30 19:16:59

标签: python ms-word word-vba

我一直在做很多关于reddit的研究,但仍无法找到我的问题的解决方案。基本上在工作中,他们要求我编写一个脚本代码,以便我可以将文本与Microsoft Word文档进行比较。如果我需要在doc1中比较的特定文本与doc2不同,那么我需要将doc2中的文本替换为doc1。这需要在Python或VBA中完成。

我一直在考虑使用docx python模块和regex来查找我需要的特定模式,这些模式将采用以下示例格式:

doc1将包含:任务12 7.120飞机7.11 VFR行动

doc2将包含:7.120飞机NAC12

NAC12与Task12相同。因此,我需要从大量文本中选择上述示例,然后确保doc2与doc1相同,如果没有将文本替换为doc1。

1 个答案:

答案 0 :(得分:1)

Word具有内置功能,可以执行您所需的操作 - 组合命令:

Screenshot of Word Combine command in the Office Ribbon

这是一个用Word的宏录制器录制的VBA宏,使用该命令合并两个文档:

Sub MergeDocuments(file1 As String, file2 As String)

    ' Merge the documents
    Application.MergeDocuments OriginalDocument:=Documents(file1), _
        RevisedDocument:=Documents(file2), Destination:= _
        wdCompareDestinationNew, Granularity:=wdGranularityWordLevel, _
        CompareFormatting:=True, CompareCaseChanges:=True, CompareWhitespace:= _
        True, CompareTables:=True, CompareHeaders:=True, CompareFootnotes:=True, _
        CompareTextboxes:=True, CompareFields:=True, CompareComments:=True, _
        CompareMoves:=True, OriginalAuthor:="Author1", RevisedAuthor:="Author2", _
        FormatFrom:=wdMergeFormatFromPrompt

    ActiveWindow.ShowSourceDocuments = wdShowSourceDocumentsBoth

    ' Accept the revisions and stop tracking changes
    ActiveDocument.AcceptAllRevisions
    ActiveDocument.TrackRevisions = False

    If ActiveWindow.View.SplitSpecial = wdPaneNone Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    Else
        ActiveWindow.View.Type = wdPrintView
    End If

End Sub
相关问题