Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text-Replace in docx and save the changed file with python-docx

I'm trying to use the python-docx module to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the old file, but with the word replaced. How am I supposed to do this?

The docx module has a savedocx that takes 7 inputs:

  • document
  • coreprops
  • appprops
  • contenttypes
  • websettings
  • wordrelationships
  • output

How do I keep everything in my original file the same except for the replaced word?

like image 783
user2617248 Avatar asked Jul 25 '13 06:07

user2617248


People also ask

How do I save changes in DOCX?

Save your documentClick FILE > Save, pick or browse to a folder, type a name for your document in the File name box, and click Save.

How do I replace a DOCX file in word?

Go to Home > Replace. Enter the word or phrase you want to replace in Find what. Enter your new text in Replace with.


1 Answers

In addition to @ramil, you have to escape some characters before placing them as string values into the XML, so this worked for me:

def escape(escapee):
  escapee = escapee.replace("&", "&")
  escapee = escapee.replace("<", "&lt;")
  escapee = escapee.replace(">", "&gt;")
  escapee = escapee.replace("\"", "&quot;")
  escapee = escapee.replace("'", "&apos;")
return escapee
like image 128
TJ_Spark Avatar answered Oct 15 '22 20:10

TJ_Spark