How do I search & replace all occurrences of a string in a ms word doc with python?

Posted by Mark on Stack Overflow See other posts from Stack Overflow or by Mark
Published on 2010-05-17T21:13:55Z Indexed on 2010/05/17 21:20 UTC
Read the original article Hit count: 253

Filed under:
|
|
|

Hello there,

I am pretty stumped at the moment. Based on http://stackoverflow.com/questions/1045628/can-i-use-win32-com-to-replace-text-inside-a-word-document I was able to code a simple template system that generates word docs out of a template word doc (in Python).

My problem is that text in "Text Fields" is not find that way. Even in Word itself there is no option to search everything - you actually have to choose between "Main Document" and "Text Fields". Being new to the Windows world I tried to browse the VBA docs for it but found no help (probably due to "text field" being a very common term).

word.Documents.Open(f)
wdFindContinue = 1
wdReplaceAll = 2
find_str = '\{\{(*)\}\}'
find = word.Selection.Find

find.Execute(find_str, False, False, True, False, False, \
True, wdFindContinue, False, False, False)

while find.Found:
    t = word.Selection.Text.__str__()
    r = process_placeholder(t, answer_data, question_data)

    if type(r) == dict:
        errors.append(r)
    else:
        find.Execute(t, False, True, False, False, False, \
        True, False, False, r, wdReplaceAll)

This is the relevant portion of my code. I was able to get around all problems by myself by now (hint: if you want to replace strings with more than 256 chars, you have to do it via clipboard, etc ...)

Hope, someone can help me.

© Stack Overflow or respective owner

Related posts about win32com

Related posts about word