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()
        
相关推荐
派大星-?4 分钟前
自动化测试五模块一框架(下)
开发语言·python
两万五千个小时35 分钟前
构建mini Claude Code:02 - 把 Bash 拆成专用工具(read_file, write_file 等)
人工智能·python
三无少女指南1 小时前
开发者环境配置:用 Ollama 实现本地大模型部署(附下载慢的解决方案
c语言·开发语言·数据库·ubuntu
henry1010101 小时前
Ansible自动化运维全攻略(AI生成)
linux·运维·python·ansible·devops
m0_531237171 小时前
C语言-操作符练习
c语言·开发语言
tod1132 小时前
C++核心知识点全解析(二)
开发语言·c++·面试经验
weixin_440401692 小时前
Python数据分析(空值、重复值检测删除与设置)
开发语言·python·数据分析
消失的旧时光-19432 小时前
C++ 多线程与并发系统取向(五)—— std::atomic:原子操作与状态一致性(类比 Java Atomic)
开发语言·jvm·c++·并发
资深web全栈开发2 小时前
CoI - 组合优于继承:解耦的艺术
android·java·开发语言