文本框中的 Python docx 段落

Ste*_*fan 8 python python-docx

有没有办法访问和操作文本框中现有 docx 文档中的文本python-docx

我试图通过迭代在文档的所有段落中找到一个关键字:

doc = Document('test.docx')

for paragraph in doc.paragraphs:
    if '<DATE>' in paragraph.text:
        print('found date: ', paragraph.text)
Run Code Online (Sandbox Code Playgroud)

如果放置在普通文本中,但不在文本框中,则可以找到它。

sca*_*nny 7

不是通过 API,至少目前还不是。您必须发现它所在的 XML 结构,并深入到 lxml 级别,也许还需要 XPath 才能找到它。像这样的事情可能是一个开始:

body = doc._body
# assuming differentiating container element is w:textBox
text_box_p_elements = body.xpath('.//w:textBox//w:p')
Run Code Online (Sandbox Code Playgroud)

我不知道 textBox 是否是这里的实际元素名称,您必须将其与 XPath 路径详细信息的其余部分一起整理出来,但这种方法可能会起作用。我经常使用类似的方法来解决尚未内置到 API 中的功能。

opc-diag是检查 XML 的有用工具。基本方法是创建一个最小的 .docx 文件,其中包含您要查找的内容的类型。然后使用 opc-diag 检查保存文件时生成的 XML Word:

$ opc browse test.docx document.xml
Run Code Online (Sandbox Code Playgroud)

http://opc-diag.readthedocs.org/en/latest/index.html

  • 这可以通过向段落添加文本框架 (framePr) 属性来实现:http://officeopenxml.com/WPparagraph-textFrames.php (2认同)

Ste*_*fan 5

仅包含格式化文本的文本框的解决方法是使用浮动的格式化表。它的样式几乎可以像文本框(框架、颜色等)一样,并且可以通过docx API.

doc = Document('test.docx')

for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                if '<DATE>' in paragraph.text:
                   print('found date: ', paragraph.text)
Run Code Online (Sandbox Code Playgroud)