using python to edit a word file?
John Henry
john106henry at hotmail.com
Thu Aug 10 17:04:02 EDT 2006
John Salerno wrote:
> I figured my first step is to install the win32 extension, which I did,
> but I can't seem to find any documentation for it. A couple of the links
> on Mark Hammond's site don't seem to work.
>
> Anyway, all I need to do is search in the Word document for certain
> strings and either delete them or replace them. Easy enough, if only I
> knew which function, etc. to use.
>
> Hope someone can push me in the right direction.
>
> Thanks.
The easiest way for me to do things like this is to do it in Word and
record a VB Macro. For instance you will see something like this:
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "save it"
.Replacement.Text = "dont save it"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.CorrectHangulEndings = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
and then hand translate it to Win32 Python, like:
wordApp = Dispatch("Word.Application")
wordDoc=wordApp.Documents.Add(...some word file name...)
wordRange=wordDoc.Range(0,0).Select()
sel=wordApp.Selection
sel.Find.ClearFormatting()
sel.Find.Replacement.ClearFormatting()
sel.Find.Text = "save it"
sel.Find.Replacement.Text = "dont save it"
sel.Find.Forward = True
sel.Find.Wrap = constants.wdFindContinue
sel.Find.Format = False
sel.Find.MatchCase = False
sel.Find.MatchWholeWord = False
sel.Find.MatchByte = False
sel.Find.CorrectHangulEndings = False
sel.Find.MatchAllWordForms = False
sel.Find.MatchSoundsLike = False
sel.Find.MatchWildcards = False
sel.Find.MatchFuzzy = False
sel.Find.Find.Execute(Replace=constants.wdReplaceAll)
wordDoc.SaveAs(...some word file name...)
Can't say that this works as I typed because I haven't try it myself
but should give you a good start.
Make sure you run the makepy.py program in the
\python23\lib\site-packages\win32com\client directory and install the
"MS Word 11.0 Object Library (8.3)" (or something equivalent). On my
computers, this is not installed automatically and I have to remember
to do it myself or else things won't work.
Good Luck.
More information about the Python-list
mailing list