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()
        
相关推荐
似水明俊德几秒前
01-C#.Net-泛型-面试题
java·开发语言·面试·c#·.net
ℳ๓₯㎕.空城旧梦16 分钟前
Python单元测试(unittest)实战指南
jvm·数据库·python
leonkay19 分钟前
Golang语言闭包完全指南
开发语言·数据结构·后端·算法·架构·golang
Allnadyy29 分钟前
【C++项目】从零实现高并发内存池(一):核心原理与设计思路
java·开发语言·jvm
雅欣鱼子酱35 分钟前
Type-C供电PD协议取电Sink芯片ECP5702,可二端头分开供电调整亮度,适用于LED灯带户外防水超亮灯条方案
c语言·开发语言
似水明俊德1 小时前
07-C#
开发语言·c#
浩子智控1 小时前
python程序打包的文件地址处理
开发语言·python·pyqt
Jackey_Song_Odd1 小时前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python
m0_662577971 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
Elnaij1 小时前
从C++开始的编程生活(20)——AVL树
开发语言·c++