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()
        
相关推荐
夏季疯1 小时前
读论文:STARS 是什么结构?一个统一的歌声自动标注框架
python
从零开始的代码生活_2 小时前
C++ 内存管理:从内存分区到 new/delete 底层原理
开发语言·c++·后端
wabs6662 小时前
关于单调栈【力扣739.每日温度的思考】
java·开发语言
光测实验室2 小时前
3种Python降噪算法实测:我把处理速度提升了20倍
python
AOwhisky2 小时前
Python 学习笔记(第三期)——流程控制核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发·流程控制
逆向编程3 小时前
Socket异常连接自动清理方案
开发语言
花花无缺3 小时前
Windows 定时执行 Python 脚本方案
python·操作系统·命令行
va学弟4 小时前
Java 网络通信编程(10):Channel 和 Selector
java·开发语言
爱吃提升4 小时前
MATLAB impulse函数脉冲响应完整实操教程
开发语言·matlab
小饕4 小时前
从 1080 Ti 到树莓派 4:Qwen2.5-0.5B Function Calling 端侧部署七步实战
开发语言·人工智能