Using python RE to replace string in Word Document?

So I am trying to run a text document to replace all text strings with "aaa" (for example) to replace it with a variable from user input, I was banging my head with multiple answers on stackoverflow to figure out and came across regexes that I have never before used, after using the tutorial a bit I just can't seem to head it up.

This is all the code I've tried, but just can't get python to actually change the text string in this Word document.

 from docx import Document
 import re

 signature = Document ('test1.docx')
 person = raw_input('Name?')
 person = person+('.docx')
 save = signature.save(person)


 name_change = raw_input('Change name?')
 line = re.sub('[a]{3}',name_change,signature)
 print line
 save
 for line in signature.paragraphs:
     line = re.sub('[a]{3}',name_change,signature)

 for table in signature.tables:
     for cell in table.cells:
        for paragraph in cell.paragraphs:
            if 'aaa' in paragraph.text:
                print paragraph.text
                paragraph.text= replace('aaa',name_change)

  save

      

Thanks in advance for any help.

+3


source to share


1 answer


for line in signature.paragraphs:
    line = re.sub('[a]{3}',name_change,signature)

      

The above code is redundant since you are updating the variable line

with re.sub, but that does not trigger the update at the actual origin as shown below:

data = ['aaa', 'baaa']
for item in data:
    item = re.sub('[a]{3}', 't', item)

print(data)
#['aaa', 'baaa']  

      



Also, you iterate over signature.paragraphs

, but just call re.sub

in all signature

every time. Try something like this:

signature = re.sub('[a]{3}', name_change, signature)
save

      

0


source







All Articles