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 分钟前
Qt常用控件(二)
开发语言·qt
西游音月7 分钟前
(12)功能实现:Qt实战项目之读写配置文件
开发语言·qt
VBA63371 小时前
VBA之Word应用第四章第五节:段落Paragraph对象的属性(一)
开发语言
whltaoin1 小时前
【Java SE】Java IO体系深度剖析:从原理到实战的全方位讲解(包含流操作、序列化与 NIO 优化技巧)
java·开发语言·nio·se·io体系
csbysj20205 小时前
jQuery 删除元素
开发语言
xxy-mm5 小时前
Javascript 中的继承
开发语言·javascript·ecmascript
quikai19817 小时前
python练习第二组
开发语言·python
熊猫_豆豆7 小时前
python 用手势控制程序窗口文字大小
python·手势识别
AI视觉网奇7 小时前
Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr
开发语言·c++·算法
wjs20248 小时前
并查集快速合并
开发语言