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()
        
相关推荐
起床学FPGA7 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
min(a,b)8 小时前
学习第17天:Agent Memory 与 MCP 协议
python·学习
x_x-F8 小时前
网络数据从网卡到用户态:一场基于内存所有权转移的接力赛
开发语言·网络·php
名字还没想好☜8 小时前
Java 线上内存泄漏排查实战:jmap 导堆、MAT 找 GC Roots 与四类常见泄漏
java·开发语言·jvm·内存泄漏
码匠许师傅8 小时前
【C++ 面试真题】聊聊 C++ 的多继承与虚继承
开发语言·c++·面试
CodeBlog-star8 小时前
LLM安全实战:提示词注入与越狱攻击防御指南
python·agent·提示词攻击·越狱攻击
小柯南敲键盘8 小时前
电商图片翻译工具推荐,批量处理主图视频字幕,免费试用
大数据·人工智能·python·音视频
我不是疯子是傻子9 小时前
Qt CAN通信周期发送抖动?实测定时器精度校准与时间戳补偿方案
开发语言·数据库·qt
比高创意品牌策划设计9 小时前
零售卖场设计软件用CAD还是SketchUp还是酷家乐
python
IT爱学堂10 小时前
尚硅谷 - 2025年3月Java+AI大模型应用开发
java·开发语言·人工智能