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()
        
相关推荐
乐观勇敢坚强的老彭17 分钟前
C++浮点数使用注意事项
开发语言·c++
wuyk55526 分钟前
38.什么是C语言?从语法到工程落地的工程师视角解读
c语言·开发语言·stm32·单片机·mcu·51单片机
库克克29 分钟前
【C++ 】内联函数
java·开发语言·c++
zh_xuan35 分钟前
java 虚拟线程
java·开发语言·虚拟线程
jason成都1 小时前
RTKLIB Java 移植踩坑复盘:卡尔曼滤波核心逻辑修复与滑坡场景实测验证
java·开发语言
中微极客1 小时前
TensorFlow模型量化实战:从精度到延迟的优化指南
人工智能·python·tensorflow
一次旅行1 小时前
【AI工具】Rust-Based CLI:用 xargs 和并行加速你的 Linux 日常
linux·开发语言·rust
老毛肚1 小时前
juc线程通信
java·开发语言·jvm
跨境数据猎手2 小时前
反向海淘实战|独立站搭建+国内电商API对接
开发语言·爬虫·架构
没钥匙的锁13 小时前
05-Java面向对象构造器与封装
java·开发语言