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 分钟前
python-字符串全解(六):正则表达式-修饰符
python·正则表达式·修饰符
灯澜忆梦7 分钟前
【Go Zap 日志库】#1 |快速上手 + 配置详解
开发语言·后端·golang
a努力。14 分钟前
四维解析Agent记忆架构:从零实战LangGraph长期记忆
java·开发语言·数据库
Wang's Blog22 分钟前
Java 项目部署之 Docker工具快速入门: Docker Compose 初识与安装
java·开发语言·docker
niucloud-admin29 分钟前
JAVA V6 多商户商城 开发文档——项目启动
java·开发语言·python
学逆向的32 分钟前
C 控制台指令
c语言·开发语言·网络安全
沫璃染墨34 分钟前
从零入门数据结构与算法(一):复杂度分析——从算法效率到时间与空间复杂度
c语言·开发语言·数据结构·笔记·算法·飞书
CCIE-Yasuo34 分钟前
个人电脑搭建AI-Qwen3-8B-学习记录
人工智能·python·学习
贾宝玉的玉宝贾1 小时前
FreeSWITCH 简单图形化界面 70 - 监听/密语的lua脚本
开发语言·junit·lua·voip·freeswitch·sip·ippbx
Wang's Blog1 小时前
Java 项目部署之 Docker工具快速入门: 镜像命令从 pull 到 load 的完整实操
java·开发语言·docker