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()
        
相关推荐
叩码以求索8 分钟前
经典算法实例分析:写字符串需要的行数
开发语言·javascript·ecmascript
我是唐青枫20 分钟前
Kotlin 运算符重载详解:为什么 a += b 有时改对象,有时换对象?
开发语言·kotlin
2zcode24 分钟前
基于MATLAB图像处理的饮料瓶识别与价格显示系统设计与实现
开发语言·图像处理·matlab
ai生成式引擎优化技术31 分钟前
从知识连接到智能组织:WSaiOS认知网络的理论框架与系统设计摘要
网络·python·plotly·django·pygame
用户83562907805135 分钟前
使用 Python 保护和取消保护 Excel 工作表和工作簿
后端·python
骑士雄师1 小时前
大模型:临时会话
开发语言·python
努力中的编程者1 小时前
STL-vector的模拟实现
开发语言·c++·算法·stl·vector
山海云端有限公司2 小时前
实战指南:用豆包图片生成API快速搭建AI绘画能力
python·ai绘画·api调用·图片生成·豆包api
ganbingfenxiang2 小时前
山西干冰零售
大数据·人工智能·python·零售
薛定猫AI2 小时前
【深度解析】GLM-5.2 与 Z-Code:AI 编程智能体的原理拆解与 Python 调用实战
开发语言·人工智能·python