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()
        
相关推荐
smchaopiao9 分钟前
Python中字典与列表合并的问题与解决方法
开发语言·python
卡尔特斯19 分钟前
Ultralytics YOLO26 自动对指定标注文件夹区分标注素材脚本与训练脚本
python·openai
敲代码的瓦龙26 分钟前
Java?面向对象三大特性!!!
java·开发语言
2501_9216494928 分钟前
期货 Tick 级数据与基金净值历史数据 API 接口详解
开发语言·后端·python·websocket·金融·区块链
野犬寒鸦31 分钟前
Redis复习记录day1
服务器·开发语言·数据库·redis·缓存
njidf32 分钟前
实战:用Python开发一个简单的区块链
jvm·数据库·python
小菜鸡桃蛋狗34 分钟前
C++——类和对象(下)
开发语言·c++
骑龙赶鸭35 分钟前
java开发项目中遇到的难点,面试!
java·开发语言·面试
Rick199338 分钟前
慢SQL优化
数据库·python·sql