首页 > 解决方案 > python-docx:查找表位于 ms word 文档中的标题名称

问题描述

我正在努力寻找表格所在的标题名称,我正在使用 python-docx 库,我想知道我可以使用它来获取表格所在的标题名称。

from docx import Document
from docx.shared import Inches
document = Document('test.docx')

tabs = document.tables

标签: pythonpython-3.xpython-docx

解决方案


您可以使用 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

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

还要检查标签列表中的数据以获取表格的标题。


推荐阅读