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()
        
相关推荐
进击的雷神10 分钟前
多展会框架复用、Next.js结构统一、北非网络优化、参数差异化配置——阿尔及利亚展爬虫四大技术难关攻克纪实
javascript·网络·爬虫·python
ZTLJQ11 分钟前
网络通信的基石:Python HTTP请求库完全解析
开发语言·python·http
xnian_11 分钟前
高并发下锁管理器,单机与分布式版
java·开发语言
不染尘.17 分钟前
背包问题BP
开发语言·c++·算法
华科大胡子17 分钟前
爬虫对抗:ZLibrary反爬机制实战分析
python
程序员buddha18 分钟前
Java面试八股文基础篇
java·开发语言·面试
进击的小头19 分钟前
第17篇:卡尔曼滤波器之概率论初步
python·算法·概率论
是梦终空19 分钟前
计算机毕业设计269—基于python+深度学习+YOLOV8的交通标志识别系统(源代码+数据库+报告)
python·深度学习·opencv·毕业设计·torch·课程设计·pyqt5
2401_8747325319 分钟前
基于C++的爬虫框架
开发语言·c++·算法
3GPP仿真实验室21 分钟前
【MATLAB源码】THz ISAC:太赫兹通感一体化链路级仿真平台
开发语言·matlab