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()
        
相关推荐
Python私教29 分钟前
AI Agent 上生产要不要开写权限?我把执行链拆成 4 道闸门
人工智能·后端·python
天才测试猿38 分钟前
软件测试知识总结(基础篇)
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
崔子末1 小时前
某影视库剧集列表以及查询接口逆向
爬虫·python
gogogo出发喽1 小时前
v3 admin
python
牛艺翔1 小时前
C++基础
开发语言·c++
键盘会跳舞1 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
美味蛋炒饭.2 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息2 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
不负岁月无痕2 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
SomeB1oody2 小时前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程