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()
        
相关推荐
郝学胜-神的一滴30 分钟前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
Thanks_ks1 小时前
SQL 注入是怎么发生的:从拼接 SQL 讲到预编译语句的防御原理
python·sqlite·orm·占位符·sql 注入·预编译语句·白名单校验
好焊孙辉2 小时前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克6052 小时前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴2 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
吃我一窝jio3 小时前
Java IO流核心分类与应用
java·开发语言·笔记
Kari114 小时前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
专注仿真4 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体
维爱智VR认知学能4 小时前
VR客户端异常诊断包白名单脱敏与受控字段构建实现
python·单元测试·软件工程·数据安全·日志脱敏
isfox5 小时前
Python 装饰器:别被 @ 符号吓到,它就是个"包装盒"
python