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()
        
相关推荐
迪康Defender2 分钟前
终端安全事后追溯能力解析:本地审计模块设计思路与落地实践
运维·开发语言·人工智能·安全·php·安全威胁分析·运维开发
郝学胜_神的一滴3 分钟前
Numpy数据处理详解 01:NumPy 从环境搭建到入门上手
人工智能·python
yujunl5 分钟前
开发一个可以用APIFOX来调试的接口
开发语言
破芽22 分钟前
python知识点小结01
python
苏辰澈22 分钟前
C++自己的族谱规则:继承详解下
c语言·开发语言·c++·visualstudio
hunter19901026 分钟前
英语作文题目
开发语言
打工仔折腾 AI29 分钟前
从零写一个CAD 05:以鼠标为中心的滚轮缩放矩阵顺序不能反
后端·python·线性代数·性能优化·矩阵·计算机外设·ai agent 实战
计算机毕业编程指导师40 分钟前
【计算机毕设选题】基于Hadoop+Spark的化妆品销售数据分析与可视化系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·hadoop·python·计算机·spark·课程设计·化妆品
谢亮_vipxieliang41 分钟前
Go基础数据类型全解
开发语言·后端·golang
泡海椒43 分钟前
JQuick-Excel 导入反向映射实战:让中文表头稳定落到业务字段
开发语言·python·excel