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()
        
相关推荐
weixin_41666007几秒前
AI 的 Markdown 复杂表格转 Word:单元格换行、合并与长文本怎么处理
人工智能·word·deepseek·鲸鱼ai助手
copilot中国版4 分钟前
Word Copilot|法律文书生产力引擎
word·copilot
Do_It_Today9 分钟前
php xml 入门学习资料
开发语言·php
熊猫钓鱼>_>17 分钟前
Kotlin Multiplatform for OpenHarmony 实战:为 Landscapist 实现图片加载适配
开发语言·kotlin·华为云·ai编程·harmonyos·鸿蒙·openharmony
*wait for?28 分钟前
利用uv安装python包,并运行jupyter
python·jupyter·uv
Nebula_g1 小时前
JavaSE加强:Commons-io框架
java·开发语言·算法·javase
FITA阿泽要努力1 小时前
第1周·第2讲|一道综合代码推演
服务器·前端·python·agent.
ggb喔1 小时前
52pojie 的桌面工具:为什么它们总在高分屏上模糊、资源管理器重启后失效
windows·python·网络安全·软件工程·个人开发·用户界面·用户体验
Do_It_Today1 小时前
php url路由入门实例
开发语言·php
小羊没烦恼!1 小时前
关于大型asp.net应用系统的架构-架构的选择
java·服务器·开发语言·前端·c#