欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > python-docx顺序读取word内容

python-docx顺序读取word内容

2024/10/25 12:20:48 来源:https://blog.csdn.net/qq_42001765/article/details/139832952  浏览:    关键词:python-docx顺序读取word内容

来源How to use Python iteration to read paragraphs, tables and pictures in word? · Issue #650 · python-openxml/python-docx (github.com)

from docx import Document
from docx.oxml.ns import qndef iter_block_items(parent):"""生成 `parent` 元素的每个块级元素,包括段落和表格。"""parent_elm = parent.element.bodyfor child in parent_elm.iterchildren():if child.tag == qn('w:p'):yield 'p', childelif child.tag == qn('w:tbl'):yield 'tbl', child# 打开文档
doc = Document("example.docx")paragraphs = doc.paragraphs
tables = doc.tablesparagraph_index = 0
table_index = 0for block_type, block in iter_block_items(doc):if block_type == 'p':paragraph = paragraphs[paragraph_index]print("Paragraph:", paragraph.text)paragraph_index += 1elif block_type == 'tbl':table = tables[table_index]table_index += 1if 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()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com