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()
        
相关推荐
深蓝电商API2 分钟前
爬虫日志分析:快速定位被封原因
爬虫·python
禾叙_9 分钟前
【netty】Channel
开发语言·javascript·ecmascript
云深处@15 分钟前
【C++11】包装器,智能指针
开发语言·c++
weixin1997010801616 分钟前
海外淘宝商品详情页前端性能优化实战
大数据·前端·python
量子炒饭大师22 分钟前
【C++入门】Cyber深度漫游者的初始链路——【类与对象】初始化成员列表
开发语言·c++·dubbo·类与对象·初始化成员列表
独自破碎E27 分钟前
BISHI43 讨厌鬼进货
android·java·开发语言
深蓝海拓31 分钟前
PySide6的QTimeLine详解
笔记·python·qt·学习·pyqt
纯.Pure_Jin(g)39 分钟前
【Python练习四】Python 算法与进阶特性实战:数组、序列化与位运算专项练习(3道经典练习带你巩固基础——看完包会)
开发语言·vscode·python
阿猿收手吧!43 分钟前
【C++】模块:告别头文件新时代
开发语言·c++
星火开发设计1 小时前
虚析构函数:解决子类对象的内存泄漏
java·开发语言·前端·c++·学习·算法·知识