I have a document (template) with the following string: "Hello, my name is Bob. Bob is a nice name." I would like to open this document using python-docx and use "find and replace" method (if exists) to change every single string "Bob" -> "Mark". At the end I would like to generate a new document with a string "Hello, my name is Mark. Mark is a nice name." How can I do that?
from docx import *
TEMPLATE_FILE = 'test_template.docx'
class generate_docx:
@staticmethod
def test():
document = Document(TEMPLATE_FILE)
body = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
body = replace(body, 'Bob', 'Mark')
savedocx('proper.docx')
AttributeError: 'Document' object has no attribute 'xpath'
Looks like you're getting python-docx v0.3.0+ API mixed in with the legacy v0.2.x API for starters. python-docx v0.3.0 is a full rewrite with an object-oriented API, which is not compatible with prior versions. Documentation for the new version is here: python-docx.readthedocs.org/en/latest/index.html. A Document instance is no longer an Element object so no longer has an .xpath method.
来源:https://stackoverflow.com/questions/23376105/search-and-replace-in-python-docx