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 分钟前
程序设计语言的特点
开发语言·数据结构·c++
超人不会飞_Jay13 分钟前
Go课程2
开发语言·后端·golang
卷无止境32 分钟前
Python生成器与惰性求值:从yield说起的一场"暂停魔法"
后端·python
Tirzano35 分钟前
java 精简使用ffmpeg
java·开发语言·ffmpeg
卷无止境41 分钟前
从一个装饰器说起:拆解 Python 的 @property
后端·python
农村小镇哥43 分钟前
python操作配置文件ini
开发语言·python
神明不懂浪漫2 小时前
【第七章】Java中的常用类
java·开发语言·前端·经验分享·笔记
love530love9 小时前
OpenClaw Windows Companion 桌面客户端 连接 LM Studio 完整配置指南
人工智能·windows·python·openclaw
程序喵大人11 小时前
【C++进阶】STL容器与迭代器 - 01 STL 容器先解决元素放在哪里
开发语言·c++·stl
cui_ruicheng11 小时前
Python从入门到实战(十六):多进程编程
开发语言·python