专业编程基础技术教程

网站首页 > 基础教程 正文

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

ccvgpt 2025-03-19 10:59:14 基础教程 3 ℃


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

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

最近发表
标签列表