使用pythondocx检索具有文档结构的文档内容

2024-09-27 23:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须从docx文件中检索表和上一段/下一段,但无法想象如何使用python-docx来获得这些内容

我可以通过document.paragraphs获得段落列表

我可以通过document.tables获得一个表列表

我怎样才能得到这样的文档元素的有序列表

[
Paragraph1,
Paragraph2,
Table1,
Paragraph3,
Table3,
Paragraph4,
...
]?

Tags: 文件文档元素内容列表tablesdocument段落
2条回答

解析为属性文档.故事,按文档顺序包含段落和表格

https://github.com/python-openxml/python-docx/pull/395

document = Document('test.docx')
document.story

python-docx还没有对此提供API支持;有趣的是,Microsoft Word API也没有。在

但是你可以用下面的代码。请注意,它有点脆弱,因为它使用了python-docx内部构件,这些内部构件可能会发生变化,但我预计它在可预见的未来会很好地工作:

#!/usr/bin/env python
# encoding: utf-8

"""
Testing iter_block_items()
"""

from __future__ import (
    absolute_import, division, print_function, unicode_literals
)

from docx import Document
from docx.document import Document as _Document
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph


def iter_block_items(parent):
    """
    Generate a reference to each paragraph and table child within *parent*,
    in document order. Each returned value is an instance of either Table or
    Paragraph. *parent* would most commonly be a reference to a main
    Document object, but also works for a _Cell object, which itself can
    contain paragraphs and tables.
    """
    if isinstance(parent, _Document):
        parent_elm = parent.element.body
        # print(parent_elm.xml)
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    else:
        raise ValueError("something's not right")

    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)


document = Document('test.docx')
for block in iter_block_items(document):
    print('found one')
    print(block.text if isinstance(block, Paragraph) else '<table>')

这里还有更多的讨论:
https://github.com/python-openxml/python-docx/issues/276

相关问题 更多 >

    热门问题