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

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

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


从 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 中的各种特定元素中提取文本,例如部分、段落、页面、行、表格、页眉和页脚。我们希望它对您有所帮助。

相关推荐

如何设计一个优秀的电子商务产品详情页

加入人人都是产品经理【起点学院】产品经理实战训练营,BAT产品总监手把手带你学产品电子商务网站的产品详情页面无疑是设计师和开发人员关注的最重要的网页之一。产品详情页面是客户作出“加入购物车”决定的页面...

怎么在JS中使用Ajax进行异步请求?

大家好,今天我来分享一项JavaScript的实战技巧,即如何在JS中使用Ajax进行异步请求,让你的网页速度瞬间提升。Ajax是一种在不刷新整个网页的情况下与服务器进行数据交互的技术,可以实现异步加...

中小企业如何组建,管理团队_中小企业应当如何开展组织结构设计变革

前言写了太多关于产品的东西觉得应该换换口味.从码农到架构师,从前端到平面再到UI、UE,最后走向了产品这条不归路,其实以前一直再给你们讲.产品经理跟项目经理区别没有特别大,两个岗位之间有很...

前端监控 SDK 开发分享_前端监控系统 开源

一、前言随着前端的发展和被重视,慢慢的行业内对于前端监控系统的重视程度也在增加。这里不对为什么需要监控再做解释。那我们先直接说说需求。对于中小型公司来说,可以直接使用三方的监控,比如自己搭建一套免费的...

Ajax 会被 fetch 取代吗?Axios 怎么办?

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发!今天给大家带来的主题是ajax、fetch...

前端面试题《AJAX》_前端面试ajax考点汇总

1.什么是ajax?ajax作用是什么?AJAX=异步JavaScript和XML。AJAX是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX可以使网页实...

Ajax 详细介绍_ajax

1、ajax是什么?asynchronousjavascriptandxml:异步的javascript和xml。ajax是用来改善用户体验的一种技术,其本质是利用浏览器内置的一个特殊的...

6款可替代dreamweaver的工具_替代powerdesigner的工具

dreamweaver对一个web前端工作者来说,再熟悉不过了,像我07年接触web前端开发就是用的dreamweaver,一直用到现在,身边的朋友有跟我推荐过各种更好用的可替代dreamweaver...

我敢保证,全网没有再比这更详细的Java知识点总结了,送你啊

接下来你看到的将是全网最详细的Java知识点总结,全文分为三大部分:Java基础、Java框架、Java+云数据小编将为大家仔细讲解每大部分里面的详细知识点,别眨眼,从小白到大佬、零基础到精通,你绝...

福斯《死侍》发布新剧照 "小贱贱"韦德被改造前造型曝光

时光网讯福斯出品的科幻片《死侍》今天发布新剧照,其中一张是较为罕见的死侍在被改造之前的剧照,其余两张剧照都是死侍在执行任务中的状态。据外媒推测,片方此时发布剧照,预计是为了给不久之后影片发布首款正式预...

2021年超详细的java学习路线总结—纯干货分享

本文整理了java开发的学习路线和相关的学习资源,非常适合零基础入门java的同学,希望大家在学习的时候,能够节省时间。纯干货,良心推荐!第一阶段:Java基础重点知识点:数据类型、核心语法、面向对象...

不用海淘,真黑五来到你身边:亚马逊15件热卖爆款推荐!

Fujifilm富士instaxMini8小黄人拍立得相机(黄色/蓝色)扫二维码进入购物页面黑五是入手一个轻巧可爱的拍立得相机的好时机,此款是mini8的小黄人特别版,除了颜色涂装成小黄人...

2025 年 Python 爬虫四大前沿技术:从异步到 AI

作为互联网大厂的后端Python爬虫开发,你是否也曾遇到过这些痛点:面对海量目标URL,单线程爬虫爬取一周还没完成任务;动态渲染的SPA页面,requests库返回的全是空白代码;好不容易...

最贱超级英雄《死侍》来了!_死侍超燃

死侍Deadpool(2016)导演:蒂姆·米勒编剧:略特·里斯/保罗·沃尼克主演:瑞恩·雷诺兹/莫蕾娜·巴卡林/吉娜·卡拉诺/艾德·斯克林/T·J·米勒类型:动作/...

停止javascript的ajax请求,取消axios请求,取消reactfetch请求

一、Ajax原生里可以通过XMLHttpRequest对象上的abort方法来中断ajax。注意abort方法不能阻止向服务器发送请求,只能停止当前ajax请求。停止javascript的ajax请求...