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()
        
相关推荐
Zzz不能停12 小时前
个人博客系统系统---测试报告【笔耕云】
python·功能测试·自动化·压力测试
互联网中的一颗神经元13 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
Wang's Blog13 小时前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
a11177614 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
郭老二14 小时前
【Python】常用模块:xmlrpc
python
名字还没想好☜14 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
威联通网络存储15 小时前
TS-h2490FU在面板制造Array段AOI缺陷画廊中的并联
python·制造
Wang's Blog16 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
接针16 小时前
UV 常用命令
python·uv
无垠的广袤17 小时前
【工业树莓派 CM0 Dev Board】扩展板设计
linux·python·嵌入式硬件·pcb设计·模块化·传感器