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()
        
相关推荐
薇茗2 分钟前
【初阶数据结构】 升沉有序的平仄 排序 3
c语言·开发语言·数据结构·算法·排序算法·文件归并排序
2401_868534783 分钟前
论快速应用开发方法及应用
大数据·python
字节高级特工4 分钟前
C++11(一) 革新:右值引用与移动语义
java·开发语言·c++·人工智能·后端
郝学胜-神的一滴5 分钟前
系统设计 012:从用户系统出发,吃透缓存、数据库与高并发设计
java·数据库·python·缓存·php·软件构建
AI科技星9 分钟前
强哥德巴赫猜想(1+1)终极证明(2026 年5月 21 日)
开发语言·人工智能·算法·计算机视觉·量子计算
人工智能导论实践课11 分钟前
奥比中光深度相机astra pro的初步ros包开发
人工智能·python
故事和你9114 分钟前
洛谷-【图论2-4】连通性问题2
开发语言·数据结构·c++·算法·动态规划·图论
Brilliantwxx15 分钟前
【C++】 二叉搜索树
开发语言·c++·算法
wj3055853789 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
为何创造硅基生物9 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言