Search and Replace in python-docx

与世无争的帅哥 提交于 2019-12-07 18:26:32

问题


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'


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!