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()
        
相关推荐
人间凡尔赛7 小时前
Next.js 16 生产级实战:Cache Components + View Transitions 完整指南
开发语言·javascript·ecmascript
满怀冰雪8 小时前
06-自动微分入门:用 Paddle 计算梯度
人工智能·python·深度学习·paddle
稚南城才子,乌衣巷风流11 小时前
函数:编程中的核心概念
开发语言·前端·javascript
阿米亚波11 小时前
【C++】流式数据输入处理(不完全整理)
开发语言·c++·笔记
大模型码小白12 小时前
JAVA 集合框架进阶:List 与 Set 的深度解析与实战
java·开发语言·人工智能·windows·语言模型·list·ai编程
皓月斯语12 小时前
【C++基础】三目运算符
开发语言·数据结构·c++
初願致夕霞13 小时前
C++懒汉单例设计详解
服务器·开发语言·c++
脱胎换骨-军哥13 小时前
C++分布式系统设计:从通信引擎到分布式共识
开发语言·c++·分布式
xlrqx14 小时前
家电清洗培训课程类别、培训方式及费用情况究竟有哪些
大数据·python
脱胎换骨-军哥14 小时前
C++零成本抽象理论深度拆解:现代C++如何在不牺牲性能的前提下提供高级语法封装
java·开发语言·c++