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 分钟前
Python开发入门:从环境搭建到第一个实用小项目
python
练习两年半的攻城狮5 分钟前
【RAG实战】知识库 BGE-M3 稀疏向量混合检索方案
python·fastapi·llamaindex
l12586510 分钟前
# LangGraph 核心架构入门:State、Node、Edge 与 Reducer 的工程理解
大数据·人工智能·python·架构·langchain·edge
mqiqe20 分钟前
AgentScope Java 2.0 集成 Chat Completions Web:一行依赖让你的 Agent 变身 OpenAI 兼容服务
java·开发语言·前端
qq_5896660529 分钟前
Java微服务介绍及应用
java·开发语言·微服务
圆圆讲门店38 分钟前
实体获客团队|基础概念与核心要点整理
人工智能·python
uoKent41 分钟前
c++中的extern关键字
开发语言·c++
牧杉-惊蛰1 小时前
将数组对象根据自定义排列
java·开发语言·算法
砚底藏山河1 小时前
【量化纯GET实战 #04】批量快照:一次 HTTP GET 取多只股票
java·python·金融·eclipse
君顾11 小时前
家校托管互通:从需求分析到系统架构的落地实践
java·开发语言·托管