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()
        
相关推荐
DLYSB_7 分钟前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
matlabgoodboy2 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
雨田言炎2 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
用户8356290780512 小时前
Python Word 转 PDF 和 PDF 转 Word 指南
后端·python
用户8356290780512 小时前
如何使用 Python 加密和保护 Word 文档
后端·python
Fluxproxy2 小时前
AI数据集采集、批量模型推理报错频发?AI项目网络稳定性优化实战
python·ai·ai编程
程序喵大人3 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody3 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
Fanta丶3 小时前
10.Python class类的定义和魔术方法
python
用户昵称1004 小时前
C/C++编程-工程实践-本地存储log的工程意义
c语言·开发语言