我可以使用 Win32 COM 替换 Word 文档中的文本吗? [英] Can I use Win32 COM to replace text inside a word document?
问题描述
我必须在某些文档中执行大量替换,问题是,我希望能够自动执行该任务.一些文档包含公共字符串,如果它可以自动化,这将非常有用.从我目前阅读的内容来看,COM 可能是这样做的一种方式,但我不知道是否支持文本替换.我希望能够在 python 中执行此任务?是否可以?你能发布一个代码片段来展示如何访问文档的文本吗?
I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported. I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?
谢谢!
推荐答案
看看 this 让您开始使用 Python 进行单词自动化.
See if this gives you a start on word automation using python.
打开文档后,您可以执行以下操作.
完成以下代码后,您可以关闭文档&打开另一个.
Once you open a document, you could do the following.
After the following code, you can Close the document & open another.
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".
您可以根据需要将其他选项设为 true/false.
The above code replaces the text "test" with "test2" and does a "replace all".
You can turn other options true/false depending on what you need.
了解这一点的简单方法是创建一个包含您想要执行的操作的宏,请参阅生成的代码 &在您自己的示例中使用它(带/不带修改参数).
The simple way to learn this is to create a macro with actions you want to take, see the generated code & use it in your own example (with/without modified parameters).
在查看 Matthew 的一些代码后,您可以执行以下操作
After looking at some code by Matthew, you could do the following
MSWord.Documents.Open(filename)
Selection = MSWord.Selection
然后将上面的VB代码翻译成Python.
注意:以下 VB 代码是不使用长语法的简写方式.
And then translate the above VB code to Python.
Note: The following VB code is shorthand way of assigning property without using the long syntax.
(VB)
With Selection.Find
.Text = "test"
.Replacement.Text = "test2"
End With
蟒蛇
find = Selection.Find
find.Text = "test"
find.Replacement.Text = "test2"
请原谅我的 Python 知识.但是,我希望你有继续前进的想法.
记得做一个 Save &完成查找/替换操作后,关闭文档.
Pardon my python knowledge. But, I hope you get the idea to move forward.
Remember to do a Save & Close on Document, after you are done with the find/replace operation.
最后,您可以调用 MSWord.Quit
(从内存中释放 Word 对象).
In the end, you could call MSWord.Quit
(to release Word object from memory).
这篇关于我可以使用 Win32 COM 替换 Word 文档中的文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!