百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

用 Python 从 Word 文档中提取文本(综合指南)

myzbx 2025-02-09 13:28 21 浏览


从 Word 文档中提取文本已成为各种目的的必不可少的任务。无论您是需要分析数据、重新调整内容的用途还是将文本合并到其他应用程序中,了解如何有效地从 Word 文档中提取文本都可以节省您的时间和精力

从 Word 文档中提取文本的 Python 库

要使用 Python 从 Word Doc 或 Docx 文档中提取文本,我们可以使用 Spire.Doc for Python 库。

Spire.Doc for Python 是一个功能丰富且易于使用的库,用于在 Python 应用程序中创建、读取、编辑和转换 Word 文件。使用此库,您可以使用多种 Word 格式,包括 Doc、Docx、Docm、Dot、Dotx、Dotm 等。此外,您还可以将 Word 文档渲染为其他类型的文件格式,例如 PDF、RTF、HTML、文本、图像、SVG、ODT、PostScript、PCL 和 XPS。

您可以通过在终端中运行以下命令从 PyPI 安装 Spire.Doc for Python:

pip install Spire.Doc

有关安装的更多详细信息,您可以查看此官方文档:如何在 VS Code 中为 Python 安装 Spire.Doc。

使用 Python 从 Word 文档中提取文本

当您需要进一步处理文档中包含的文本信息时,从 Word 文档中提取文本会很有帮助。使用 Spire.Doc for Python,您可以使用 Document.GetText() 函数轻松获取 Word 文档的文本。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Extract the text of the document
document_text = document.GetText()

# Write the extracted text into a text file
with open("Output/DocumentText.txt", "w", encoding="utf-8") as file:
    file.write(document_text)

document.Close()

使用 Python 从 Word 文档中的某个部分中提取文本

Word 文档可能包含不同的部分,每个部分都包含特定内容。Spire.Doc for Python 使您能够使用 Document.Sections[index] 属性访问 Word 文档中的特定部分。访问后,可以通过循环访问节中的段落,然后使用 Paragraph.Text 属性获取每个段落的文本,从节中提取文本。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档的特定部分中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Get the first section in the document
section = document.Sections[0]

# Create a list to store the extracted text
section_text = []

# Iterate through the paragraphs in the section
for i in range(section.Paragraphs.Count):
    paragraph = section.Paragraphs[i]
    # Extract the text of each paragraph and append it to the list
    section_text.append(paragraph.Text)

# Write the extracted text into a text file
with open("Output/SectionText.txt", "w", encoding="utf-8") as file:
    file.write("\n".join(section_text))

document.Close()

使用 Python 从 Word 文档中的段落中提取文本

若要从 Word 文档中的特定段落中提取文本,可以使用 Section.Paragraphs[index] 属性访问该段落,然后使用 Paragraph.Text 属性获取该段落的文本。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档中的特定段落中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Get the first section in the document
section = document.Sections[0]

# Get the second paragraph in the section
paragraph = section.Paragraphs[1]
# Extract the text of the paragraph
para_text = paragraph.Text

# Write the extracted text into a text file
with open("Output/ParagraphText.txt", "w", encoding="utf-8") as file:
    file.write(para_text)

document.Close()

使用 Python 从 Word 文档中的页面中提取文本

从技术上讲,Word 文档中没有“页面”的概念,因为它们基本上是作为流文档设计的。为了便于页面级操作,Spire.Doc for Python 提供了 FixedLayoutDocument 类,该类允许您将 Word 文档的内容组织到页面中。通过使用此类及其属性,您可以毫不费力地获取 Word 文档中特定页面的文本。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档中的特定页面中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Create an object of the FixedLayoutDocument class and pass the Document object to the class constructor as a parameter
layoutDoc = FixedLayoutDocument(document)

# Access the first page of the document
layoutPage = layoutDoc.Pages[0]

# Get the text of the first page
page_text = layoutPage.Text

# Write the extracted text into a text file
with open("Output/PageText.txt", "w", encoding="utf-8") as file:
    file.write(page_text)

document.Close()

使用 Python 从 Word 文档中的一行中提取文本

从 Word 文档中的一行中提取文本允许在行级别对文本进行详细分析或操作。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档中的特定行中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")

# Create an object of the FixedLayoutDocument class and pass the Document object to the class constructor as a parameter
# This step is to transfer the document into a fixed layout document
layoutDoc = FixedLayoutDocument(document)

# Access the first page of the document
layoutPage = layoutDoc.Pages[0]

# Get the first line of the first column on the page
line = layoutPage.Columns[0].Lines[0]

# Extract the text of the first line
line_text = line.Text

# Write the extracted text into a text file
with open("Output/LineText.txt", "w", encoding="utf-8") as file:
    file.write(line_text)

document.Close()

使用 Python 从 Word 文档中的表格中提取文本

Word 文档通常包含以表格格式组织数据的表格。从表中提取数据允许对 Word 文档中的表格信息进行结构化数据提取、转换或分析。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档的特定表中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Table.docx")

# Get the first section in the document
section = document.Sections[0]

# Get the first table in the section
table = section.Tables[0]

# Create a list to store the extracted table data
table_data = []

# Iterate through the rows in the table
for i in range(table.Rows.Count):
    row = table.Rows[i]
    # Iterate through the cells in each row
    for j in range(row.Cells.Count):
        cell = row.Cells[j]
        # Iterate through the paragraphs in each cell
        for k in range(cell.Paragraphs.Count):
            # Extract data from each paragraph
            paragraph = cell.Paragraphs[k]
            text = paragraph.Text
            # Append the data to the list
            table_data.append(text + "\t")
    table_data.append("\n")

# Write the extracted data into a text file
with open("Output/TableText.txt", "w", encoding = "utf-8") as text_file:
    for data in table_data:
        text_file.write(data)

document.Close()

使用 Python 从 Word 文档中的页眉和页脚中提取文本

页眉和页脚是通常位于 Word 文档中每页顶部和底部的部分。它们通常包含文档标题或其他补充内容等信息。

下面是一个简单的示例,演示如何使用 Python 和 Spire.Doc for Python 从 Word 文档的页眉和页脚中提取文本:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("HeaderAndFooter.docx")

# Get the first section in the document
section = document.Sections[0]

# Get the header of the section
header = section.HeadersFooters.Header
# Get the footer of the section
footer = section.HeadersFooters.Footer

# Create a list to store the extracted header and footer text
header_footer_text = []
header_footer_text.append("Header Text:")

# Get the text of the header
for i in range(header.Paragraphs.Count):
    headerPara = header.Paragraphs[i]
    header_footer_text.append(headerPara.Text)

header_footer_text.append("Footer Text:")

# Get the text of the footer
for i in range(footer.Paragraphs.Count):
    footerPara = footer.Paragraphs[i]
    header_footer_text.append(footerPara.Text)

# Save the extracted text to a text file
with open("Output/HeaderFooterText.txt", "w", encoding="utf-8") as file:
    file.write("\n".join(header_footer_text))    

document.Close()

结论

本文演示了如何使用 Python 从 Word 文档中提取文本。此外,它还解释了如何使用 Python 从 Word 中的各种特定元素中提取文本,例如部分、段落、页面、行、表格、页眉和页脚。我们希望它对您有所帮助。

相关推荐

MORROR ART:毫无音质可言,真的只是好看而已...

今天早上我在微博上发了一条短视频,内容是某款网红音箱正在放声歌唱——这玩意就是此前曾经在网上挺火的所谓“悬浮歌词音箱”。这款产品是我同事收到的礼品,但她嫌在家里放着没用,所以拿到公司里做我们的拍摄道具...

「JS优化篇」你的 if - else 代码肯定没我写的好

作者:小生方勤转发链接:https://mp.weixin.qq.com/s/JzOQ_OwAYoP5Ic1VBtCZNA前言最近部门在对以往的代码做一些优化,我在代码中看到一连串的if(){}el...

细聊微内核架构在前端的应用「干货」

作者:semlinker转发链接:https://mp.weixin.qq.com/s/ywc98dS4TVB4t3L2tIyk8g一、微内核架构简介1.1微内核的概念微内核架构(Microke...

ThreeJS 入门教程(一) 是选择桌面的固守还是云原生?

导读:最近我购置了一台新的电脑,硬盘空间只有1T。我很担心这个电脑还能用多久。性能限制或者空间的限制,都使得在未来3-5年内,这个电脑会被淘汰。但是,基于云APP的使用,老的电脑是足够了,而且,我们也...

推荐三款正则可视化工具「JS篇」(正则在线调试)

作者:代码先森转发链接:https://mp.weixin.qq.com/s/rw29yKBwti5sIsx2GKG9pw前言最近老王对可视化非常着迷。例如,算法可视化、正则可视化、Vue数据劫持可...

Javascript 多线程编程的前世今生

作者:jolamjiang腾讯技术工程转发链接:https://mp.weixin.qq.com/s/87C9GAFb0Y_i5iPbIL5Hzg为什么要多线程编程大家看到文章的标题《Javasc...

Pug 3.0.0正式发布,不再支持 Node.js 6/8

作者:李俊辰前端之巅转发链接:https://mp.weixin.qq.com/s/q-49Gf-SFijeu7d2MqztIQ前言近日,Pug3.0.0正式发布,Pug原名Jade,是由...

36个工作中常用的JavaScript函数片段「值得收藏」

作者:Eno_Yao转发链接:https://segmentfault.com/a/1190000022623676前言如果文章和笔记能带您一丝帮助或者启发,请不要吝啬你的赞和收藏,你的肯定是我前进的...

深入JavaScript教你内存泄漏如何防范

作者:大道至简转发链接:https://mp.weixin.qq.com/s/0w6aWwpR3MAJnmyLwDnAzA前言一般情况下,忽视内存管理不会对传统的网页产生显著的后果。这是因为,用户刷新...

由浅入深,66条JavaScript面试知识点(七)

作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录由浅入深,66条JavaScript面试知识点(一)由浅入深,66...

用STM32做了个电子秤,成本仅两位数,精度高!解析一下原理

俗话说得好!人在胖,秤在看!所以,我想DIY一个精度高的体重秤!并希望它不只能称体重:还能像这样称克重(可设置KG,G,最低可称100克)……这样一来,做甜品的时候,还能拿来应应急。保姆级教程,记录在...

前端开发需要了解常用7种JavaScript设计模式

作者|Deven译者|王强策划|小智转发链接:https://mp.weixin.qq.com/s/Lw4D7bfUSw_kPoJMD6W8gg前言JavaScript中的设计模式指的是...

毛姆的一个手法|王培军(毛姆作品简介)

鲁本斯画《海伦娜·芙尔曼肖像》钱锺书在《宋诗选注》文同小传中说:“具体的把当前风物比拟为某种画法或某某大画家的名作”,是“从文同正式起头”。如钱先生所举的:“峰峦李成似,涧谷范宽能”,“独坐水轩人不到...

欣赏 | 朝戈:我渴望找到直达心灵的永恒

朋友,通过艺术让我们共同感知世界的永恒与不朽。——朝戈橙色的人物117X71cm布面油画2003包与陈185cm×103cm2007年白色80cm×40cm2009年光布面油画-Light-Oilo...

Web页面如此耗电!到了某种程度,会是大损失

现在用户上网大多使用移动设备或者笔记本电脑。对这两者来说,电池寿命都很重要。在这篇文章里,我们将讨论影响电池寿命的因素,以及作为一个web开发者,我们如何让网页耗电更少,以便用户有更多时间来关注我们的...