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()
        
相关推荐
泡海椒1 分钟前
评分系统最佳实践:JQuick-Java实现权重、阈值动态配置评分
java·人工智能·python
三克的油2 分钟前
java-学习1
java·开发语言·学习
weixin199701080164 分钟前
《二手ERP对接的对账机制:按日巡检 + 自动补偿,消灭“幽灵订单“》(附Python源码)
python
m0_547486668 分钟前
《Python数据分析与实践》全套PPT课件(杭州电子科技大学)
python·数据分析
星期八不上发条15 分钟前
智能指针是什么?使用场景,循环引用解决办法,面试回答
开发语言·c++·stl
OKkankan24 分钟前
Python 基础进阶(三):从函数、类到 asyncio 与 FastAPI 后端开发实战
开发语言·python
智购科技自动售卖机厂家27 分钟前
设备一到夏天就频繁跳闸,从启动电流追到压缩机电容~YH
数据结构·人工智能·python·eclipse
科技林总1 小时前
Poetry‌介绍
python
东木月1 小时前
PyCharm 集成 Claude Code 插件:安装、配置与使用指南
python·pycharm·编辑器
泡海椒1 小时前
jquick-pdf 防止 PDF 内容分页断裂:keepTogether 属性妙用
java·开发语言·pdf