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()
        
相关推荐
阿俊-全栈开发24 分钟前
扩展设计解析:LikeShop Go 版商城营销活动的插件化扩展设计思路
开发语言·微服务·golang·likeshop·likeshop源码
干啥啥不行,bug第一名32 分钟前
EAFNOSUPPORT、EPROTOTYPE、EOPNOTSUPP:socket 的三层参数没有对齐
开发语言·php
期货资管源码1 小时前
内盘期货中远期与跨品种套利开发笔记:价差、配对与执行细节
笔记·python·量化交易·期货·套利
我要见SA姐11 小时前
用生活化类比当钥匙,一键打开 C++ 入门大门
java·开发语言·c++
1024奇点2 小时前
第四篇 第 03 课
开发语言·ide·后端
AI大模型-小雄2 小时前
Codex 如何自动修复项目 Bug?从错误定位到测试验证的实战教程
python·程序员·bug·ai编程·codex·chatgpt plus·chatgpt pro
大彼方..2 小时前
CSDN-02-开发环境介绍与安装
c语言·开发语言·stm32
风月说与山鬼2 小时前
五、python基础——集合、映射类型
python
BK贝壳3 小时前
初始化一亿个全 True 或全 False:bool-hybrid-array 的 TruesArray/FalsesArray 占位构造本机实测
开发语言·数据结构·python·性能优化·numpy
编程见习者3 小时前
外卖员招聘助手
人工智能·python