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()
        
相关推荐
hunzi_18 分钟前
PHP商城源码:构建高效电商平台的利器
开发语言·php
lpfasd12322 分钟前
模板方法模式(Template Method Pattern)
java·开发语言·设计模式·模板方法模式
SDL大华37 分钟前
【备忘】PHP web项目一般部署办法
开发语言·php
٩( 'ω' )و2601 小时前
qt信号与槽--01
开发语言·qt
灏瀚星空1 小时前
高频交易技术:订单簿分析与低延迟架构——从Level 2数据挖掘到FPGA硬件加速的全链路解决方案
人工智能·python·算法·信息可视化·fpga开发·架构·数据挖掘
Hello.Reader1 小时前
在多云环境透析连接ngx_stream_proxy_protocol_vendor_module
后端·python·flask
zh_199951 小时前
Spark面试精讲(上)
java·大数据·数据仓库·python·spark·数据库开发·数据库架构
小猫咪怎么会有坏心思呢1 小时前
华为OD机考-找座位-逻辑分析(JAVA 2025B卷)
java·开发语言·华为od
泪光29291 小时前
洛谷自己创建的一个小比赛【c++】
开发语言·c++
开开心心就好1 小时前
高效账号信息管理工具,可安全随机生成密码
javascript·安全·docker·智能手机·pdf·word·excel