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()
        
相关推荐
csbysj202018 分钟前
PHP If...Else 语句详解
开发语言
sinat_3834373626 分钟前
Laravel 8 中实现错误日志与调试日志分离的完整配置指南
jvm·数据库·python
清水白石0087 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
yaoxin5211238 小时前
390. Java IO API - WatchDir 示例
java·前端·python
武帝为此9 小时前
【数据清洗缺失值处理】
python·算法·数学建模
zhangchaoxies10 小时前
如何在 Go 中安全复制接口指针所指向的值
jvm·数据库·python
曲幽10 小时前
FastAPI + Pydantic 模型终极实战手册:从能跑就行到固若金汤,这些技巧你一定用得上
python·fastapi·web·model·field·pydantic·validator·basemodel
Halo_tjn10 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色10 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手10 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift