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()
        
相关推荐
xyz_CDragon2 分钟前
OpenClaw 局域网调用 Ollama 本地大模型:完整配置与踩坑指南
python·ai编程·集成学习·ollama·deepseek·openclaw
threelab3 分钟前
Three.js 几何图形变换 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
极光代码工作室5 分钟前
基于NLP的论文关键词提取系统
python·深度学习·自然语言处理·nlp
无限进步_6 分钟前
Linux进程等待——wait、waitpid与僵尸进程
linux·运维·服务器·开发语言
野生技术架构师9 分钟前
Java 23 种设计模式:从踩坑到精通 —— 开篇及系列介绍
java·开发语言·设计模式
Wang ruoxi10 分钟前
Pygame 小游戏——数独
开发语言·python·pygame
吠品12 分钟前
处理 Python 类继承中那些变来变去的初始化参数
linux·前端·python
人道领域15 分钟前
【LeetCode刷题日记】90.子集Ⅱ--- 归纳题解
java·开发语言·leetcode
会Tk矩阵群控的小木16 分钟前
小红书矩阵软件:基于Python+ADB的多设备批量管理自动化脚本实战
运维·python·adb·矩阵·自动化·新媒体运营·个人开发
ch.ju22 分钟前
Java Programming Chapter 4——Characteristics of inheritance
java·开发语言