有趣生活

当前位置:首页>科技>python word文档处理库python办公自动化之Word篇

python word文档处理库python办公自动化之Word篇

发布时间:2026-07-25阅读(0)

导读Python-docx模块基础入门之一Word文件读取操作1.打开Word文档document读取存在的文件,要用到docx库中的Documentdocum....Python-docx 模块基础入门之一 Word文件读取操作1.打开Word文档document

读取存在的文件,要用到docx库中的Document

document = Document(file_path),file_path表示要打开的Word路径,没有参数表示新建文档。

代码:

from docx import Documentdocument = Document(test.docx)

docx打开文件

获取段落paragraph

一个document文档包括一个或者多个段落,都在document的paragras属性中,document.paragraphs返回所有段落对象的列表。

例如paragrahps = document.paragraphs

paragraphs[0] --> 表示第1段对象

paragraphs[1] --> 表示第2段对象

……

len(pargraphs) --> 查看文档有多少个自然段

代码:

paragraphs = document.paragraphs # paragraphs表示得到的所有段落列表type(paragraphs) # 返回列表p1 = paragraphs[0] # p1表示第一段段落对象len(paragraphs) # 检查文档一共有多少段

段落对象

获取段落paragraph文本内容

.text用于获取文本内容,不仅可以获取段落对象的,还可以获取块对象的文本内容

代码:以p2第二段对象为例

p2.text

获取文字块run及其文本内容

一个段落有多个文本块run对象组成,我们可以通过paragraph.runs获取所有块对象,然后通过.text获取其内容,这里以第4段为例p4 = paragraphs[3]

代码:

for run in p4.runs:print(run.text)

完整遍历文档document文本内容

代码:

for paragraph in document.paragraphs:for run in paragraph.runs: print(run.text)

遍历文档document的表格table对象

和openpyxl 操作excel类似,table表格遍历采取三级循环样式

A:按照行遍历

for table in document.tables:for row in table.rows: for cell in row.cells: print(cell.text)

B: 按照列遍历

for table in document.tables:for column in table.columns: for cell in column.cells: print(cell.text)

概况一下:要获得文本,都可以使用.text,不管是段落paragraph,还是run,或者是table表格的cell单元格。

TAGS标签:  python  word  文档  处理  python wor  d文档处理库pyth

Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图