search replace in Word from Python
greg munger
gmunger at nospam.lpiweb.com
Mon May 19 12:40:16 EDT 2003
I have a simple perl script that uses the COM interface to convert a few
MS Word styles to html (based on word2pod.pl by Jan Dubois). I would
rather use Python than Perl, but I can't get one thing to work in Python.
At one point I do the following (in Perl):
my $Search = $Doc->Content->Find;
my $Replace = $Search->Replacement;
$Search->Clearformatting;
$Replace->Clearformatting;
# convert bold styles
$Search->Font->{Bold} = 1;
$Replace->{Text} = '<b>^&</b>';
$Search->Execute({Replace => wdReplaceAll});
# convert italic
$Replace->Clearformatting;
$Search->Clearformatting;
$Search->Font->{Italic} = 1;
$Replace->{Text} = '<i>^&</i>';
$Search->Execute({Replace => wdReplaceAll});
This modifies the current document, then I read it and print it
preserving this formatting.
I have been trying to get the equivalent code to work with Python. I did
run the MakePy utility to generate the COM constants. In the example
below I used a constant for the Bold replacement, and used the value for
the italic replacement. I don't get an error, but I don't see any bold or
italic elements either.
def fixStyles( doc):
search = doc.Content.Find
replace = search.Replacement
search.ClearFormatting();
replace.ClearFormatting();
search.Font.Bold = 1
replace.Text = "<b>^&,</b>"
search.Execute( Replace = constants.wdReplaceAll)
search.ClearFormatting();
replace.ClearFormatting();
search.Font.Italic = 1
replace.Text = "<i>^&,</i>"
search.Execute( Replace = 2)
search.ClearFormatting();
replace.ClearFormatting();
Can anyone see what I am doing wrong?
thanks,
Greg Munger
More information about the Python-list
mailing list