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()
        
相关推荐
钱栈up22 分钟前
扫完 3.5 万文件后,我发现了 521 组散落的同名文件
爬虫·python·数据分析
黄权光22 分钟前
AI智能体项目实战记录(01):开发环境搭建之conda的安装与配置
python
Wokoo723 分钟前
Selenium 核心 API 解析(三)
python·功能测试·selenium
在世修行34 分钟前
智学文枢:技术选型
python·技术选型
程序喵大人40 分钟前
【C++入门】编译链接模型 - 07 链接器怎样把符号对上号
开发语言·c++·编译器·编译链接·链接器
用户83562907805141 分钟前
如何使用 Python 将 PDF 转换为 PPTX 文件
后端·python
微三云 - 廖会灵 (私域系统开发)1 小时前
供应链系统实战:多渠道订单聚合与分布式库存一致性方案总结
开发语言·分布式·php
学逆向的1 小时前
C 数据溢出与精度丢失
c语言·开发语言·网络安全
我命由我123451 小时前
Function Calling 模型
人工智能·python·学习·ai·学习方法·ai编程·ai写作
霸道流氓气质2 小时前
AgentFlow 入门与实战:Task-Based 并发、EWMA 动态调度与四道门禁的 Java 生产级编排
java·开发语言