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()
        
相关推荐
qq_161111275 分钟前
Pillow项目深度解析:Python图像处理的终极武器
图像处理·python·pillow·开源库·历史解析
梅孔立5 分钟前
Pi-Agent 终极极简配置文档(Java+Vue+Python爬虫 4-5千文件项目)
java·vue.js·python
李可以量化10 分钟前
Redis Client 从了解到精通(二)下:String 类型进阶操作全解
redis·git·python·量化交易·qmt
wy31362282111 分钟前
Git——ignore让项目的 target 目录真正被忽略(忽略其他文件也是同样的道理)
开发语言·git
格林威11 分钟前
C#图像分块处理:图像按行或按块(Tile)切分,多个 CPU 核心同时处理不同的区域
开发语言·图像处理·人工智能·机器学习·计算机视觉·c#·工业相机
leisoo809718 分钟前
财报舞弊预警系统实战用Python挖掘应收存货异常因子 IG50免费开源股票数据API接口
开发语言·python
君顾119 分钟前
AI新零售线上商城系统实战:架构设计与开发全流程指南
java·开发语言·零售
wind1003226 分钟前
Outdated Visual C++ Redistributable 过时 VC++ 运行库报错修复
开发语言·c++
吾皇斯巴达32 分钟前
O_DIRECT与gcsfuse的go程序中实现内存页面对齐
开发语言·后端·golang
光电的一只菜鸡1 小时前
高通tuning中eis需要调什么
java·开发语言·前端