简体   繁体   中英

Using python RE to replace a string in Word Document?

So i am trying to run through a word document to replace all text strings with 'aaa' (just for example) to replace it with a variable from user input, i have been bashing my head with a few answers on stackoverflow to figure out and came across Regular expressions which i have never used before, after using a tutorial for a bit I just can't seem to get my head round it.

This is all the code i have tried exampling but just can't seem to 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

Thank you in advance for any help.

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

The above code is redundant since you update the variable line with the re.sub, but it doesn't cause an update in 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 are iterating over signature.paragraphs but just calling re.sub on the entirety of signature everytime. Try something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM