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()
        
相关推荐
逻极7 分钟前
OpenClaw「Clawdbot/Moltbot」 深入解析:核心架构深度剖析
python·ai·架构·agent·ai编程·moltbot·openclaw
sayang_shao9 分钟前
C++ ONNX Runtime 与 Python Ultralytics 库实现 YOLOv8 模型检测的区别
c++·python·yolo
曹牧9 分钟前
Java:强类型转换
开发语言·python
wuguan_12 分钟前
C#之线程
开发语言·c#
LXS_35716 分钟前
STL - 函数对象
开发语言·c++·算法
爱学习的阿磊18 分钟前
Python入门:从零到一的第一个程序
jvm·数据库·python
木千20 分钟前
Qt5.15.2安装MSVC2019编译器
开发语言·qt
naruto_lnq22 分钟前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
仟濹24 分钟前
【Java加强】1 异常 | 打卡day1
java·开发语言·python
去往火星27 分钟前
Qt6 CMake 中引入 Qt Linguist 翻译功能
开发语言·qt