【发布时间】: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-docx iter_block_items”以获取有关此主题的讨论和解决方案。特别是,此页面详细介绍:github.com/python-openxml/python-docx/issues/40
标签: python python-docx