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·审计日志·pyside·数据清理·孤儿文件
qq_406981035 分钟前
什么是顶层 const什么是底层const
开发语言·c++
日日大王学编程10 分钟前
DeepSeekHarness开源Agent底座详解
python·开源·deep learning
Eider199824 分钟前
python基础语法之并发基础练习
开发语言·python
长和信泰光伏储能29 分钟前
探索绿色能源:光伏发电的渠道与应用
python·能源
#麻辣小龙虾#29 分钟前
网页布局css中flex+margin的组合布局技巧
开发语言·前端·javascript
郝学胜-神的一滴31 分钟前
AI 编程智能体 20:技术栈选型与架构落地全攻略
人工智能·python·架构·langchain·1024程序员节·智能体
云和数据.ChenGuang32 分钟前
python和java的try
java·开发语言·python
我是唐青枫33 分钟前
Kotlin Inheritance(继承)详解:语法、原理、实战 Demo
开发语言·kotlin
ly768943 分钟前
从 OpenAPI 到多语言 SDK 生成:Java 服务端契约漂移与生成器版本治理
java·开发语言·openapi·java 21·版本兼容·契约漂移·sdk 生成