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()
        
相关推荐
勇闯逆流河14 分钟前
【C++】C++11(下)
开发语言·c++
云栈开源日记17 分钟前
Python 开发技术栈梳理:从数据库、爬虫到 Django 与机器学习
数据库·爬虫·python·学习·机器学习·django
青衫码上行18 分钟前
【Java Web学习 | 第15篇】jQuery(万字长文警告)
java·开发语言·前端·学习·jquery
胡萝卜3.06 小时前
掌握C++ map:高效键值对操作指南
开发语言·数据结构·c++·人工智能·map
电子_咸鱼6 小时前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
哈茶真的c7 小时前
【书籍心得】左耳听风:传奇程序员练级攻略
java·c语言·python·go
沐知全栈开发7 小时前
ionic 选项卡栏操作详解
开发语言
曹牧7 小时前
C#中,#region和#endregion
开发语言·c#
顾安r7 小时前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
蒙小萌19937 小时前
Swift UIKit MVVM + RxSwift Development Rules
开发语言·prompt·swift·rxswift