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()
        
相关推荐
星空椰1 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
白露与泡影2 小时前
2026大厂Java面试题大全!牛客网最新版
java·开发语言
凯瑟琳.奥古斯特2 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
风之所往_2 小时前
Python 3.4 新特性全面总结
python
雪度娃娃2 小时前
转向现代C++——在意为改写的函数添加 override
开发语言·c++
太阳上的雨天3 小时前
任何格式的文件转Markdown
python·ai
yaoxin5211233 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
喵星人工作室3 小时前
C++火影忍者1.1.2
开发语言·c++
weixin_468466853 小时前
纳米 AI 搜索新手极速上手指南
人工智能·python·深度学习·搜索引擎·ai·语言模型·自然语言处理
凯瑟琳.奥古斯特3 小时前
数据库原理选择题精选
数据库·python·职场和发展