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()
        
相关推荐
熊猫钓鱼>_>4 分钟前
鸿蒙PC高分屏与键鼠交互适配:DPI缩放、右键菜单一次讲清
开发语言·笔记·华为·ai编程·harmonyos·鸿蒙·鸿蒙心迹
終不似少年遊*9 分钟前
【Skill】为中型研发团队制作的敏捷迭代AI副驾Skill
人工智能·python·华为云·agent·ai编程·skill
呆萌的代Ma10 分钟前
python使用ThreadPoolExecutor自带队列将多线程变串行执行
python
echome88816 分钟前
Python 正则表达式:5 个日常够用的模式
python·正则表达式
SunnyDays101132 分钟前
Java 操作 Word 脚注和尾注:添加、读取与删除
java·word
SunnyDays101134 分钟前
Java 为 Word 添加页码:隐藏封面页码、从指定页开始编号、奇偶页页码设置等
java·word·页码
octopus_c37 分钟前
C++ 运算符重载详解 && 日期类的实现
开发语言·c++
吴名氏.39 分钟前
Java转AI Agent教程(第二周)超时重试与错误分类
java·人工智能·python·分类·ai agent
青少儿编程课堂40 分钟前
2026蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:堆排序与优先队列解析
c++·python·算法·bfs·信息学竞赛
Eiceblue41 分钟前
用 Python 给 Word 文档加水印:文字、图片与批量处理
开发语言·vscode·python·word