python-docx顺序读取word内容

来源How to use Python iteration to read paragraphs, tables and pictures in word? · Issue #650 · python-openxml/python-docx (github.com)

python 复制代码
from docx import Document
from docx.oxml.ns import qn

def iter_block_items(parent):
    """
    生成 `parent` 元素的每个块级元素,包括段落和表格。
    """
    parent_elm = parent.element.body

    for child in parent_elm.iterchildren():
        if child.tag == qn('w:p'):
            yield 'p', child
        elif child.tag == qn('w:tbl'):
            yield 'tbl', child

# 打开文档
doc = Document("example.docx")

paragraphs = doc.paragraphs
tables = doc.tables

paragraph_index = 0
table_index = 0

for block_type, block in iter_block_items(doc):
    if block_type == 'p':
        paragraph = paragraphs[paragraph_index]
        print("Paragraph:", paragraph.text)
        paragraph_index += 1
    elif block_type == 'tbl':
        table = tables[table_index]
        table_index += 1
        if table:
            print("Table:")
            for n_r, row in enumerate(table.rows):
                print(f"    Row {n_r}: ")
                for n_c, cell in enumerate(row.cells):
                    print(f"        Column {n_c}:", cell.text, end=' ')
                print()
        
相关推荐
霍霍的袁8 分钟前
【C++初阶】缺省参数(默认参数)详细讲解
开发语言·c++·算法
I Promise3416 分钟前
多传感器融合&模型后处理C++工程师面试参考回答
开发语言·c++·面试
hef28822 分钟前
SQL和Python怎么选?数据分析工具实战指南
python·sql·数据分析
徐安安ye23 分钟前
FlashAttention长程依赖建模:局部+全局的Hybrid Spiral结构设计
python·深度学习·机器学习
2501_9327502628 分钟前
Java反射机制基础入门
java·开发语言
IT策士44 分钟前
Django 从 0 到 1 打造完整电商平台:商品排序与浏览量统计
后端·python·django
霍霍的袁44 分钟前
【C++初阶】函数重载详细讲解
开发语言·c++·算法
threelab1 小时前
Three.js 黑洞引力效果着色器 | 三维可视化 / AI 提示词
开发语言·javascript·着色器
godspeed_lucip1 小时前
LLM和Agent——专题3: Agentic Workflow 入门(4)
人工智能·python
godspeed_lucip1 小时前
LLM和Agent——专题3: Agentic Workflow 入门(2)
网络·人工智能·python