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()
        
相关推荐
skilllite作者几秒前
从“记忆”到“项目 Wiki”:我在 SkillLite 里实现了一套 Markdown-only LLM Wiki 自动维护机制
开发语言·jvm·人工智能·后端·架构·rust
㳺三才人子几秒前
簡介 python 文字轉語音
开发语言·python
zh157023几秒前
如何在 macOS 中使用 launchd 每分钟执行一次 PHP 脚本
jvm·数据库·python
阿正呀1 分钟前
HTML怎么显示计量值_HTML meter标签应用场景【指南】
jvm·数据库·python
炘爚4 分钟前
C++(整理合集)
开发语言·c++
buhuizhiyuci4 分钟前
[QT]QT入门的项目创建和项目代码的介绍
开发语言·qt
qq_283720054 分钟前
Python+OpenCV 计算机视觉:从零入门 AI 视觉开发
人工智能·python·计算机视觉
qq_413847404 分钟前
如何脱机维护表空间数据文件_OFFLINE与ONLINE状态的切换场景
jvm·数据库·python
Brilliantwxx5 分钟前
【C++】认识标准库STL(1)
开发语言·c++·笔记·程序人生·算法
XMYX-07 分钟前
20 - Go 互斥锁:Mutex 与并发安全
开发语言·golang