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()
        
相关推荐
卷无止境22 分钟前
当独立开发者也能造出3A画质的游戏:Godot引擎深度解析
后端·python·godot
在世修行33 分钟前
从零打造 C# 工业视觉检测系统(八):Modbus RTU 协议解析与 PLC 剔除控制实战
开发语言·c#
sunburn-1 小时前
Java 队列全面详解:从入门到面试实战
java·开发语言·汇编·ide·idea
AI直播技术杂谈1 小时前
AI直播推流链路中延迟优化的通用技术方案
开发语言·人工智能·php
vx-程序开发1 小时前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
Dxy12393102162 小时前
python 中的 APScheduler 使用详解
开发语言·python
染指11102 小时前
76.高级RAG-后检索器(时间排序)
人工智能·python·llama_index·llamaindex
福如意如我心意3 小时前
java虚拟线程和Go协程的区别
开发语言
weixin_440784113 小时前
Java基础常见题
java·开发语言·python·java基础
(Charon)4 小时前
【C++】多线程死锁:产生原因、复现与解决方法
开发语言·c++·算法