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()
        
相关推荐
武天旭3 分钟前
AI安全--AI大模型的毒性偏见与安全对齐实践
人工智能·python·深度学习
w_zero_one38 分钟前
递归算法(一)
java·开发语言·算法
视觉小萌新1 小时前
AI Class 3 · Chapter 2-3:函数、异常、文件读写+JSON / JSONL 读写(小白版)
人工智能·python·json
Julien20042 小时前
管理机密(一)
运维·服务器·开发语言·学习方法
Chen_harmony2 小时前
七、STL与string类
开发语言·c++
沐晓时光2 小时前
C语言入门,字符串和字符串函数知识讲解
c语言·开发语言
小小张说故事2 小时前
Python 的 obj.x 到底按什么顺序找?拆开数据描述符、实例字典和 __getattr__ 那条优先级链
python
xxxiugou1232 小时前
C++命名空间与引用全解析
开发语言·c++
用户11481867894843 小时前
水印的实现方式逻辑
前端·python
贾公子3 小时前
从单条内容到账号维度——AIGC 风险评分的工程实现
后端·python