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()
        
相关推荐
老一岁6 分钟前
c问题总结(2)
c语言·开发语言
Ming_studying7 分钟前
Python批量压缩图片:支持JPG_PNG_WebP、尺寸限制与CSV报告
开发语言·图像处理·python·pillow·图片压缩
大熊背7 分钟前
ISP图像处理中大数乘法溢出处理(一)
人工智能·python·算法·溢出处理
风月说与山鬼11 分钟前
JS闭包详解
开发语言·javascript
何以解忧,唯有..12 分钟前
Python协程详解:从生成器到async/await的完整指南
开发语言·python
奶茶树17 分钟前
【C++】13. C++11新特性【上】
c语言·开发语言·c++·git·github
hhzz20 分钟前
智慧校园13类视频异常检测:数据集与预训练模型全攻略
人工智能·pytorch·python·深度学习·目标检测·机器学习
SomeB1oody21 分钟前
【RustyML入门】7.4. 按需裁剪与模块化集成
开发语言·后端·机器学习·rust·教程
浩腾数字多媒体29 分钟前
如何判断专业电子留言厂家适配条件?
大数据·人工智能·python
会编程的吕洞宾43 分钟前
DeepAgents In Action学习(Third)
python·学习·django