Python从 Word 文档中提取文本和图片

519 阅读3分钟

Word文档在日常工作中被应用广泛, 文本和图片是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

您也可以参考本教程获取详细安装步骤:如何在 VS Code 中安装 Spire.Doc for Python

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()

提取文本.png

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()

提取图像.png

---本文完---