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()
        
相关推荐
星恒随风5 分钟前
C++ 类和对象入门(三):拷贝构造、赋值运算符重载和深浅拷贝
开发语言·c++·笔记·学习
RickyWasYoung6 分钟前
【Matlab】科研绘图配色-极简版
开发语言·matlab
凡人叶枫7 分钟前
Effective C++ 条款03:尽可能使用 const
linux·开发语言·c++·嵌入式开发
lie..8 分钟前
基于大模型的智能客服系统部署与使用(二):接入前端可视化界面
人工智能·python
光影62713 分钟前
Python接口自动化测试----Requests库基础入门
开发语言·python·测试工具·pycharm·自动化
程序媛_13 分钟前
【Python】连接PostgreSQL获取手机验证码
开发语言·python·postgresql
ch.ju15 分钟前
Java Programming Chapter 4——Inherited call
java·开发语言
Kobebryant-Manba17 分钟前
学习参数管理
pytorch·python·深度学习
是有头发的程序猿18 分钟前
竞品分析 + 用户洞察自动化|基于 item_review 评论接口 + 多 AI Agent 实现淘宝评论全量采集与智能分析(附python源码)
java·python·自动化
信看18 分钟前
Jetson Orin Quectel QMI 拨号上网
开发语言·python