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()
        
相关推荐
SilentSamsara几秒前
综合实战:用 Python 做一个待办事项管理器(CLI 版)
开发语言·python·青少年编程·pycharm
HAPPY酷2 分钟前
UE5 C++ 避坑指南:暴力移除 Electronic Nodes 插件,回归纯净开发
开发语言·c++·ue5
huipeng9263 分钟前
分布式服务部署详解
java·开发语言·spring cloud·微服务
步辞3 分钟前
CSS如何对表单输入框获取焦点时实现标签上浮过渡
jvm·数据库·python
eqwaak03 分钟前
4 月技术快讯|Rust 1.90 正式发布,系统级开发再进化
开发语言·后端·rust
小此方3 分钟前
Re:思考·重建·记录 现代C++ C++11篇 (四)C++ Lambda 全解析:编译器是如何为你生成仿函数的?
开发语言·c++·c++11·现代c++
秦歌6664 分钟前
RAG-6-高级RAG实战案例:自适应路由 + 自评估重写 + 网络回退
java·服务器·前端·人工智能·python
Brilliantwxx6 分钟前
【C++】初认识模版
开发语言·c++
财经资讯数据_灵砚智能6 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年4月27日
人工智能·python·信息可视化·自然语言处理·ai编程
qq_432703666 分钟前
c++怎么在不使用STL的情况下利用Win32 API进行低级文件IO【底层】
jvm·数据库·python