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()
        
相关推荐
她说..几秒前
MySQL数据处理(增删改)
java·开发语言·数据库·mysql·java-ee
BD_Marathon3 分钟前
【JavaWeb】ServletContext_域对象相关API
java·开发语言
qq_229058018 分钟前
运行djando项目 配置启动类 label_studio包含前后端启动方法
python·django
invicinble12 分钟前
javase-异常体系
开发语言·spring boot
qq_2515335914 分钟前
查找 Python 中对象使用的内存量
开发语言·windows·python
yaoxin52112317 分钟前
269. Java Stream API - Map-Filter-Reduce算法模型
java·python·算法
Bruce_kaizy40 分钟前
C++树形数据结构————树状数组、线段树中“逆序对”的问题
开发语言·数据结构·c++
❥ღ Komo·41 分钟前
K8s蓝绿发布实战:零停机部署秘籍
java·开发语言
梨落秋霜44 分钟前
Python入门篇【函数】
开发语言·python
电饭叔1 小时前
利用类来计算点是不是在园内《python语言程序设计》2018版--第8章18题第3部分
开发语言·python