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()
        
相关推荐
北极星日淘2 分钟前
煤炉自动代拍功能开发 | Python 异步任务实现批量下单
开发语言·python·自动化
光之后裔8 分钟前
用自定义数据集微调PP-OCRv5文本检测、识别模型
python·机器学习·ocr
体验家21 分钟前
体验家 XMPlus 网页端问卷 SDK 技术解析:用几行 JavaScript 实现精准场景触发与防打扰机制
开发语言·前端·javascript
2301_7644413329 分钟前
基于AI的本地文件归档智能管理工具梳理
人工智能·python·算法·目标检测·交互
二十七剑31 分钟前
LangGraph 源码深度解析:Node 节点 Protocol 与 StateNodeSpec 核心机制
开发语言·python
AC赳赳老秦33 分钟前
OpenClaw + 云数据库运维:自动备份、扩容、迁移 RDS/MySQL 云数据库
运维·开发语言·数据库·人工智能·python·mysql·openclaw
醉城夜风~33 分钟前
类和对象III
开发语言·c++
Tbisnic35 分钟前
AI大模型学习第十二天:Coze工作流与智能体开发
人工智能·python·ai·大模型·智能体·coze
冷小鱼35 分钟前
高级研发编码习惯:从规范到艺术,再到AI+时代的人机协同
java·开发语言·python·编码习惯