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()
        
相关推荐
CCblandy9 分钟前
缓存淘汰实测:一次全表扫描把 LRU 命中率从 46% 打到 38%,W-TinyLFU 守住 50% 却贵 11 倍
后端·python·缓存·性能优化·架构
BuHuaX14 分钟前
Lua 与 ToLua:运行机制及热更新原理
开发语言·unity·junit·c#·lua
xys_67816 分钟前
深挖C++:C++入门基础
开发语言·c++
汤米粥17 分钟前
cmd手动创建的Django项目怎么用社区版Pycharm运行起来
python·pycharm·django
涵玥22 分钟前
python题目练习12-小玉家的电费//小玉在游泳//小鱼的航程
python·python每日一练·洛谷题目
计算机毕业编程指导师27 分钟前
基于深度学习的花卉图像分类识别系统(PyTorch + ResNet50 + Django)
pytorch·python·深度学习·分类·毕业设计·迁移学习·图像分类
2601_962885721 小时前
vnpy 用什么数据源?A 股历史行情接入与 BarData 映射
python
日日大王学编程1 小时前
deerflow-memory-design-blog
python·langchain·开源
幻境如梦丶皆为虚1 小时前
从零写一个 DSH 插件:在左侧菜单栏加一个「测试」
开发语言·javascript·ecmascript