在平时工作中,我们可能需要从大量的Word文档中收集特定的信息。通过提取文本,我们可以快速获取所需的数据,并对其进行整理和分析。这在进行市场调研、舆情监测、法律文件分析等领域非常有用。Word文档中可能包含与文本相关的图表、插图或其他类型的图片。提取这些图片可以帮助我们获取原始的图像数据,以进行后续的分析、编辑或转换。例如,在出版业中,提取图片可以用于排版和重新设计,而在教育领域,我们可以将图片用于制作教学资料或课件。Python从word文档中提取文本或图片具有自动化、灵活性和可扩展性的优势。本文将介绍如何使用Spire.Doc for Python从Word文档中提取文本或图片。
- Python从 Word 文档中提取文本
- Python 从 Word 文档中提取图片
安装Spire.Doc for Python
使用Spire.Doc for Python 提取 Word 文档内容之前,需要先将其引入到项目中。可以从 Spire.Doc for Python 官方网站下载,或直接 pip 安装。代码如下:
pip install Spire.Doc
Python提取word 文档中的文本
Spire.Doc for Python 支持从 Word 文档中直接提取文本并将其保存为文本文件,这样用户就可以不受设备限制地查看和编辑文本内容。以下是从 Word 文档中提取文本的详细步骤:
- 创建 Document 类的对象。
- 使用 Document.LoadFromFile() 方法加载 Word 文档。
- 使用 Document.GetText() 方法从文档中获取文本字符串。
- 调用 WriteAllText() 方法将字符串写入文本文件。
from spire.doc import *
from spire.doc.common import *
def WriteAllText(fname:str,text:List[str]):
fp = open(fname,"w")
for s in text:
fp.write(s)
fp.close()
inputFile = "Sample.docx"
outputFile = "GetText.txt"
#创建一个Document类的对象
document = Document()
#加载Word文档
document.LoadFromFile(inputFile)
#提取文本
text = document.GetText()
#将字符串写入文本文件中
WriteAllText(outputFile, text)
document.Close()
Python提取Word文档中的图片
通过提取图像,用户可以轻松地将文档中的图像数据导入其他应用程序进行进一步处理,或是分享到社交媒体。Spire.Doc for Python允许用户从 Word 文档中提取图像并将其保存到指定路径。以下是详细操作步骤:
- 创建 Document 类的对象。
- 使用 Document.LoadFromFile() 方法加载 Word 文档。
- 创建一个复合对象队列。
- 创建一个 Images对象存储提取的图像。
- 遍历文档树,并通过遍历每个节点的子节点来检查复合对象或图片对象。
- 检查子元素是否为合成对象。如果是,则将其添加到队列中,以便进一步处理。
- 检查子元素是否为图片对象。如果是,则提取其图像数据并将其添加到提取的图像列表中。
- 使用 imageFile.write() 方法将图片保存到特定文件夹。
import queue
from spire.doc import *
from spire.doc.common import *
import os
outputPath = "ExtractImage/"
inputFile = "Sample1.docx"
if not os.path.exists(outputPath):
os.makedirs(outputPath)
#创建Document对象
document = Document()
#加载示例文档
document.LoadFromFile(inputFile)
#将document添加到nodes队列中
nodes = queue.Queue()
nodes.put(document)
#创建Image列表
images = []
#遍历
while nodes.qsize() > 0:
node = nodes.get()
for i in range(node.ChildObjects.Count):
child = node.ChildObjects.get_Item(i)
if child.DocumentObjectType == DocumentObjectType.Picture:
picture = child if isinstance(child, DocPicture) else None
dataBytes = picture.ImageBytes
images.append(dataBytes)
elif isinstance(child, ICompositeObject):
nodes.put(child if isinstance(child, ICompositeObject) else None)
#将图像数据写入到文件
for i, item in enumerate(images):
fileName = "Image-{}.png".format(i)
with open(outputPath+fileName,'wb') as imageFile:
imageFile.write(item)
document.Close()
全文完--