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()
        
相关推荐
.千余4 分钟前
【C++】 String 常用操作:增删查改 | 查找 | 截取 | IO
java·服务器·开发语言·c++·笔记·学习
码云骑士6 分钟前
【Java基础】JDK安装常见问题教辅-从踩坑到排雷
java·开发语言
c2385610 分钟前
C++ lambda 表达式详细介绍
开发语言·c++
KaMeidebaby14 分钟前
卡梅德生物技术快报|细胞周期检测抗原流式分析:参数调试、软件拟合与问题排查
网络·人工智能·python·网络协议·tcp/ip·算法·机器学习
艾莉丝努力练剑17 分钟前
【QT】界面优化:QSS
linux·运维·开发语言·网络·qt·计算机网络·udp
jieyucx20 分钟前
站在云原生高并发天花板:拆解 Go 语言 GMP 模型与 I/O 多路复用的神级配合
开发语言·云原生·golang
caimouse20 分钟前
Reactos 第 3 章 内存管理 — 【下篇】换出、Section、池
c语言·开发语言·windows·架构
无忧.芙桃23 分钟前
debug实例与分析(一)
开发语言·c++·算法
zmzb010324 分钟前
Python课后习题训练记录Day124
开发语言·python
geovindu25 分钟前
python: Broadcast Pattern
开发语言·python·设计模式·广播模式