How do I search & replace all occurrences of a string in a ms word doc with python?
- by Mark
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.