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()
        
相关推荐
万法若空几秒前
C/C++基本类型表示范围
c语言·开发语言·c++
yijianace4 分钟前
Python爬虫实战:BooksToScrape 多线程爬取与图片下载
开发语言·爬虫·python
LadenKiller4 分钟前
期货多品种轮动标的池:天勤 query_quotes 筛品种写法
python·区块链
郑洁文5 分钟前
基于Python+回归分析的电子产品需求数据分析与预测
python·数据分析·回归·电子产品需求数据·电子产品数据分析
凡人叶枫10 分钟前
Effective C++ 条款15:在资源管理类中提供对原始资源的访问
linux·开发语言·c++·stm32·单片机
IT策士10 分钟前
Redis 从入门到精通:Python 操作 Redis 进阶
数据库·redis·python
swordbob11 分钟前
Spring Boot 2.0 改 CGLIB 后,接口实现是否有影响
java·开发语言·spring
AI人工智能+电脑小能手15 分钟前
【大白话说Java面试题 第106题】【并发篇】第6题:synchronized 锁的锁对象可以是什么?
java·开发语言·面试
质造者16 分钟前
Python 本地 RAG 实战 | Ollama+ChromaDB 实现 PDF 离线智能问答
开发语言·python·pdf·大模型·rag
骑士雄师16 分钟前
18.1 星系案例:多智能体宇宙探索系统(学习langgraph 的存储知识)
windows·python·学习