在 python-docx 中搜索和替换 [英] Search and Replace in python-docx
问题描述
我有一个包含以下字符串的文档(模板):你好,我叫 Bob.Bob 是个好名字."我想使用 python-docx 打开此文档并使用查找和替换"方法(如果存在)更改每个字符串Bob"->Mark".最后,我想生成一个带有字符串你好,我的名字是马克.马克是个好名字"的新文档.我该怎么做?
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' 对象没有属性 'xpath'
AttributeError: 'Document' object has no attribute 'xpath'
推荐答案
看起来您将 python-docx v0.3.0+ API 与用于初学者的旧版 v0.2.x API 混合在一起.python-docx v0.3.0 是一个完全重写的面向对象的 API,与之前的版本不兼容.新版本的文档在这里:python-docx.readthedocs.org/en/latest/index.html.Document 实例不再是 Element 对象,因此不再具有 .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.
这篇关于在 python-docx 中搜索和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!