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()
        
相关推荐
Luminous.8 分钟前
C语言--day30
c语言·开发语言
码云骑士19 分钟前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python
何以解忧,唯有..25 分钟前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
謓泽34 分钟前
C语言不是语法,是通往机器的地图。
c语言·开发语言
云水一下35 分钟前
从零开始学 PHP 系列(一):PHP 的前世今生与开发环境搭建
开发语言·php
飞天狗11139 分钟前
零基础JavaWeb入门——第五课第二小节:九大内置对象 · 第2个:response(响应对象)
java·开发语言
DJ斯特拉40 分钟前
axios快速使用
开发语言·前端·javascript
xingpanvip1 小时前
星盘接口开发文档:本命盘接口指南
android·开发语言·css·php·lua
闵孚龙1 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
于先生吖1 小时前
教育类Java实战项目:在线错题整理平台分层架构设计与接口源码解析
java·开发语言