1. Word 文档
虽然安装的时候使用的是:pip install pyton-docx,但是导入的模块是import docx。.docx文件的结构为:
在最高一层,Document 对象表示整个文档。Document 对象包含一个 Paragraph 对象的列表,表示文档中的段落(用户在 Word 文档中输入时,如果按下回车,新的段落就开始了)。每个 Paragraph 对象都包含一个 Run 对象的列表。
Word 文档中的文本不仅仅是字符串。它包含与之相关的字体、大小、颜色和其他样式信息。在Word 中,样式是这些属性的集合。一个 Run 对象是相同样式文本的延续。当文本样式发生改变时,就需要一个新的 Run 对象。示例:
1) 读取 Word 文档
向docx.Document()传入一个word文档,得到Document对象。Document.paragraphs获得Paragraph对象列表。Paragraph.runs取得Run对象列表。Paragraph对象和Run对象都有text属性。示例:
import docx
# 创建Document对象
doc = docx.Document('demo.docx')
# 创建Pagraph对象列表,并调用Pagraph对象的text属性
paragraph = doc.paragraphs
print(paragraph[0].text)
# 创建Run对象列表,并调用Run对象的Text属性
run = paragraph[1].runs
print(run[2].text)