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()
        
相关推荐
小小测试开发6 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想6 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波7 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
AAA大运重卡何师傅(专跑国道)7 小时前
【无标题】
开发语言·c#
copyer_xyf7 小时前
Python 异常处理
前端·后端·python
XBodhi.8 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧8 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy8 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.8 小时前
【01】Python 机器学习
开发语言·python
为爱停留8 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python