2009-06-25 97 views
4

我必须在一些文档中执行大量的替换操作,事情是,我希望能够自动执行该任务。某些文档包含常用字符串,如果可以自动执行,这将非常有用。从我目前阅读的内容来看,COM可能是这样做的一种方式,但我不知道是否支持文本替换。 我想能够在python中执行此任务?可能吗?你能发布一段代码片段来展示如何访问文档的文本吗?我可以使用Win32 COM替换word文档中的文本吗?

谢谢!

回答

8

看看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”并执行“全部替换”。
您可以根据自己的需要将其他选项设置为true/false。

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

编辑:看着马修一些代码后,你可以做以下

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" 

原谅我的蟒蛇知识。但是,我希望你有想法向前迈进。
在完成查找/替换操作后,记得做一次保存&关闭文档。

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

+0

感谢您的回答! – Geo 2009-06-25 19:50:41

+0

伯尼的答案包括实际完整的Python代码。这个答案可能更简洁,并且包含更完整的python。 – Epu 2013-03-27 21:41:29

3

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

+0

感谢您的回答! – Geo 2009-06-25 21:13:18

10

我喜欢到目前为止的答案;
这里有一个测试的例子(从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') 
+1

感谢您的回答! – Geo 2009-06-25 20:12:42

2

您也可以做到这一点使用的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 

相关问题