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()
        
相关推荐
czq_268671948722 分钟前
Python打卡第36天
pytorch·python·深度学习
计算机编程指导师24 分钟前
【计算机毕设】基于Hadoop+Spark的美国互联网银行贷款数据可视化分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·hadoop·python·数据分析·spark·毕业设计·贷款
Starry-sky(jing)40 分钟前
onnxruntime 安装后 GPU 没加速?3 条命令确认它跑在 CPU 还是 GPU
python·gpu·cuda·onnxruntime·推理加速
步行cgn41 分钟前
Spring AOP 实战:安全日志
python·安全·spring
北i43 分钟前
Dubbo 默认超时重试:把下游打雪崩的隐形放大器
开发语言·qt·dubbo
诺伦1 小时前
OpenAI Agents API 公测拆解:托管编排+持久会话+自有沙箱搭一条自动增长流水线 | RiseClaw玄策
python·openai·ai agent·营销自动化·agent编排
10mAh1 小时前
【Java】ArrayList 遍历删除为什么报错?三种写法与漏删复现
java·开发语言·windows
坊钰1 小时前
【LangGraph框架入门级】2. 图核心概念:State、Node、Edge 与 Reducers
python·ai编程·langgraph
wewowilling1 小时前
AI大模型开发--01Python基础(无废话)
开发语言·python·函数
小猴子爱上树1 小时前
跨境电商AI图片翻译工具:批量图片翻译、视频字幕翻译与智能抠图一站式解决
大数据·人工智能·python·音视频