【问题标题】:Parse Docx file content w.r.t. headings解析 Docx 文件内容 w.r.t.标题
【发布时间】:2019-09-18 14:58:46
【问题描述】:

我想使用 python-docx 解析 docx 文件的结构及其内容。该文件的结构使用“标题 1”到“标题 6”。任何标题下的内容都可以是表格元素的形式。

我了解如何使用 python-docx 提取标题和表格彼此独立

    doc = Document("file.docx")
    for paragraph in doc.paragraphs:
        if paragraph.style == doc.styles['Heading 1']:
            indent = 1
            result.append('- %s' % paragraph.text.strip())
        elif paragraph.style == doc.styles['Heading 2']:
            indent = 2
            result.append('  ' * indent + '- %s:' % paragraph.text.strip())
        elif paragraph.style == doc.styles['Heading 3']:
            indent = 3
            result.append('  ' * indent + '- %s:' % paragraph.text.strip())
        [...]
        else:
            [...]

    for table in doc.tables:
        if _is_content(table.row_cells(0)[0].text):
            result.add_table(table)

我的问题是保留结构。如何在带有标题的表格下找到源文档中的表格?

【问题讨论】:

标签: python python-docx


【解决方案1】:

您可以使用 xml 从 docx 文件中提取结构化信息。 试试这个:

doc = Document("file.docx")
headings = [] #extract only headings from your code
tables = [] #extract tables from your code
tags = []
all_text = []
schema = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
for elem in doc.element.getiterator():
    if elem.tag == schema + 'body':
        for i, child in enumerate(elem.getchildren()):
            if child.tag != schema + 'tbl':
                 node_text = child.text
                 if node_text:
                     if node_text in headings:
                         tags.append('heading')
                     else:
                         tags.append('text')
                     all_text.append(node_text)
             else:
                 tags.append('table')
        break

在上面的代码之后,您将获得标签列表,其中将显示文档标题、文本和表格的结构,然后您可以从列表中映射相应的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2013-02-23
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2019-03-04
    相关资源
    最近更新 更多