精通文本分析——NLP 项目的数据收集与抽取

75 阅读20分钟

2.1 为什么你应该学习 NLP

如今各个领域的数据可获得性呈爆炸式增长。全球每天产生的数据量平均以艾字节(exabytes)计,达到数百艾字节。无论从哪个标准看,这都是极其庞大的数据量,其中美国贡献显著。只有在对这些数据进行适当分析并最终得出可执行项(actionable items)时,这些数据对政府和企业才有用。在这个以数据为驱动的世界里,自然语言处理(NLP)是一个推荐使用的工具,它支持各类行业分析基于文本的、结构化与非结构化数据。

企业可获得的主要文本数据源通常包括社交媒体交互、客户反馈以及其他类似来源。对数据的正确分析有助于通过分析市场趋势更好地理解客户,并最终做出明智决策。通过实施基于 NLP 的文本分析技术,公司可以获得更高的运营效率,并在战略决策过程中提供强有力的支持。

在企业中有效实施 NLP 可以减少员工与管理层的手工劳动并提升整体效率。大量文本数据的处理可以实现完全自动化。成功实施 NLP 的结果是能够及早发现潜在问题,并生成针对动态变化市场所需的最适当行动项,从而缩短整体响应时间,为管理层节省大量宝贵时间,以便投入到其它关键业务活动中。

因此,企业可以利用 NLP 的预测能力来预测客户需求及相关市场变动。通过自动生成这些宝贵的前瞻性洞见并据此调整主动策略,企业能够获得竞争优势。由此可见,NLP 是一项关键工具,能够生成可执行的业务洞见,帮助在当今快速演变的市场中高效运营并提升公司盈利表现。

(请提供一个案例研究或商业示例,说明某知名公司如何通过收集并处理 NLP 数据获得洞见。)

2.2 在哪里找到 NLP 项目的数据(文本语料库)

现实中的实时 NLP 业务项目通常利用大量语言数据。在 NLP 社群中,这类数据称为文本语料库(text corpora)。另有一个相关术语:词汇资源(lexical resources)。下面讨论它们是什么以及它们与文本语料库的关系。

文本语料库是大规模的书面文本集合。许多语料库被设计为在不同类别之间包含有代表性的内容混合,这类专门语料库用于研究不同专业群体如何使用语言。另一方面,词汇资源类似于字典,有助于理解文本语料库中出现的词的含义。文本语料库与词汇资源结合,能为分析与学习任一语言提供全面的手段。

文本语料库包含人类在不同语境中使用语言的真实示例;词汇资源则提供语料库中单词的定义与说明。二者结合,学习者既能看到词在真实语境中的使用,又能理解词义、在句中的用法及它们之间的关系,从而使语言学习与分析更为有效。图 2-1 展示了用于情感分析教程的一些数据处理技术。我们将在后续章节定义、讨论并使用每一种数据处理技术,敬请关注!

image.png 图 2-1——一些按顺序排列的常见文本预处理技术

在图 2-1 中,源文本是项目特定的文本语料库,如果项目需要还可以结合相应的词汇资源。接下来,我们将讨论相关概念并用 Python 代码展示其实时使用方法。

本章的主要目标是解释可用于 NLP 项目的文本数据来源。先从一些熟悉的例子开始。如果你熟悉 Python 的 Seaborn 库,可能会遇到下列(不一定是文本的)内置数据集。

提示(Tips)
Iris
Penguins
Flights
Diamonds
Titanic
Exercise
MPG
Planets

这些是内置在 Seaborn 中的数据集,易于加载与使用。下面看示例代码(Listing 2-1);你可以看出这并非 100% 的文本数据集,但它用于演示如何方便地上传数据并在后续代码中使用。通常情况下,你可能会加载 .csv、.xlsx 文件或通过网页抓取等方法上传数据。与此类似,Python 中面向 NLP 的库(如 NLTK)也包含便于在 NLP 项目中使用的内置文本数据(文本语料库)。

import seaborn as sns
tips = sns.load_dataset("tips")
print(tips.head())
    total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2

示例 2-1——从 Python Seaborn 轻松加载内部数据

与 Seaborn 示例并行,现在讨论来自 NLTK Python 库的一些内置文本语料库。这些文本数据可以直接用于你的分析(NLP)项目。

NLTK 是构建处理自然语言(如英语等)的 Python 程序的主流平台之一。NLTK 提供对 50 多个语料库与词汇资源的内置、易用接口。一些常用的包括 Brown、Gutenberg、Reuters、Inaugural Address Corpus 以及 WordNet 3.0(英语)。下面的代码(Listing 2-2)展示了如何访问 NLTK 中的流行文本语料库和词汇资源。

2.2.1 访问一些流行的 NLTK 文本语料库

# 如果尚未安装 nltk,可跳过或运行如下
!pip install nltk
# 安装后需要下载数据。示例中未展示输出以节省空间。
import nltk
nltk.download('all')

示例 2-2——访问流行文本语料库与词汇资源

2.2.2 访问 Gutenberg 语料库

from nltk.corpus import gutenberg
print(gutenberg.fileids())
['austen-emma.txt', 'austen-persuasion.txt', 'austen-sense.txt', 'bible-kjv.txt', 'blake-poems.txt', 'bryant-stories.txt', 'burgess-busterbrown.txt', 'carroll-alice.txt', 'chesterton-ball.txt', 'chesterton-brown.txt', 'chesterton-thursday.txt', 'edgeworth-parents.txt', 'melville-moby_dick.txt', 'milton-paradise.txt', …(续)']

代码输出表示 NLTK 的 Gutenberg 文本语料库中可用的文件 ID(file identifiers)集合。每个文件 ID 代表语料库中包含的一部文学作品的文本文件。

# 读取某一文件的文本
hamlet = gutenberg.words('austen-persuasion.txt')
print(hamlet[:50])
['[', 'Persuasion', 'by', 'Jane', 'Austen', '1818', ']', 'Chapter', '1', 'Sir', 'Walter', 'Elliot', ',', 'of', 'Kellynch', 'Hall', ',', 'in', 'Somersetshire', ',', 'was', 'a', 'man', 'who', ',', 'for', 'his', 'own', 'amusement', ',', 'never', 'took', 'up', 'any', 'book', 'but', 'the', 'Baronetage', ';', 'there', 'he', 'found', 'occupation', 'for', 'an', 'idle', 'hour', ',', 'and', 'consolation']

让我们访问更多此类语料库。

2.2.3 访问 Reuters 语料库

from nltk.corpus import reuters
file_ids = reuters.fileids()[:10]
print(file_ids)
[....., 'test/14833', 'test/14839', 'test/14840', 'test/14841', 'test/14842', ....(续)]

Reuters 语料库中的类别并非互斥。我们可以请求某篇文档所属的多个主题,也可以请求被包含在多个类别中的多个文档。

# 语料库方法接受单个或多个 file ID
reuters.categories(['test/14828', 'test/14829'])
['crude', 'grain', 'nat-gas']

file_ids = reuters.fileids(['crude', 'grain'])[:10]
print(file_ids)
['test/14828', 'test/14829', 'test/14832', ...(续)]

reuters.words('test/14843')[:5]
['SUMITOMO', 'BANK', 'AIMS', 'AT', 'QUICK']

reuters.words(categories=['crude', 'grain', 'nat-gas'])
['CHINA', 'DAILY', 'SAYS', 'VERMIN', 'EAT', '7', '-', ...]

2.2.4 访问 Brown 语料库

from nltk.corpus import brown
categories = brown.categories()[:5]
print(categories)
[...., 'editorial', 'fiction', ...(续)]

sentences = brown.sents(categories=['adventure', 'belles_lettres'])[:2]
for sentence in sentences:
    print(' '.join(sentence))
# 输出示例:
# Northern liberals are the chief supporters of civil rights and of integration .
# They have also led the nation in the direction of a welfare state .

2.2.5(重复标题)访问 Gutenberg 语料库

(原文此处有一段对 Reuters 与 Gutenberg 说明的交叉。下面的示例继续说明如何获取 Gutenberg 中的文件列表并读取文本。)

import nltk
file_ids = gutenberg.fileids()[:3]
print(file_ids)
['austen-emma.txt', …(续)]

# 以 "Emma by Jane Austen" 为例
emma_text_sample = nltk.corpus.gutenberg.words('austen-emma.txt')
len(emma_text_sample)
# 返回示例:192427

2.2.6 访问 Web 与 Chat 文本
该语料库包含来自 Firefox 讨论论坛的内容、《加勒比海盗》电影剧本、在纽约偶然听到的对话、定制广告和葡萄酒评论等内容。访问 Web 和 Chat Text 的代码如下:

from nltk.corpus import webtext
for fileid in webtext.fileids():
    print(fileid, webtext.raw(fileid)[:30], '...')
# 输出示例:
# firefox.txt Cookie Manager: "Don't allow s ...
# grail.txt SCENE 1: [wind] [clop clop clo ...
# pirates.txt PIRATES OF THE CARRIBEAN: DEAD ...
# singles.txt 25 SEXY MALE, seeks attrac old ...
# wine.txt Lovely delicate, fragrant Rhon ...

NLTK 还有一个即时消息聊天会话语料库(nps_chat),组织为 15 个文件:

from nltk.corpus import nps_chat
chatroom = nps_chat.posts('10-19-20s_706posts.xml')
first_10_messages = chatroom[123][:10]
print(first_10_messages)

2.2.7 访问 NLTK 词汇资源

要点如下:

  • NLTK 包含多个词汇资源。
  • 最重要的词汇资源之一是 WordNet。
  • WordNet 是一个巨大的英语词汇数据库,将词组织为多个同义词集合(synsets)。
from nltk.corpus import wordnet as wn
synonyms = wn.synsets('book')
print(synonyms)
# 输出类似:[Synset('book.n.01'), Synset('book.n.02'), …(续)]

输出代表单词 “book” 的同义词集合(synsets)列表。示例中 book 表示被定义同义词集合的单词,n 表示词性(此处为名词),01 表示该词义在同义词集合中的序号。

# 获取定义与示例(仅打印前五条)
for i, syn in enumerate(synonyms):
    if i >= 5:
        break
    print(syn.definition())
    print(syn.examples())

示例输出(节选)可能为:

  • “a written work or composition that has been published (printed on pages bound together)”
    示例:['I am reading a good book on economics']
  • “physical objects consisting of a number of pages bound together”
    示例:['he used a large book as a doorstop']
  • “a compilation of the known facts regarding something or someone”
    示例:["Al Smith used to say, `Let's look at the record'", 'his name is in all the record books']
  • “a written version of a play or other dramatic composition; used in preparing for a performance”
    示例:[]
  • “a record in which commercial accounts are recorded”
    示例:['they got a subpoena to examine our books']

输出给出了每个词义的定义与示例句,均来自 WordNet,并展示了该单词在不同语境中的用法。

(注:有关 NLTK 基本语料库功能的更多方法,可参见 nltk.corpus.reader 与 NLTK 官方教程:<www.nltk.org/howto>。强烈建议…

2.3 从 Word 文件提取数据

Microsoft Word 文档在专业、科研与学术环境中被广泛使用。Word 文件常包含以文本形式呈现的有价值数据,可能包括业务报告、文学文章与研究论文等。这些数据可用于多种 NLP 项目,例如信息抽取、情感分析与文本分类。对 Word 文件的处理可以产出丰富的结构化与非结构化文本内容,有助于构建全面的 NLP 模型,从而自动化并优化业务流程,快速获得洞见以支持数据驱动的决策。

以这种格式存储的信息可以与来自数据库、网站及其它文本格式(或来源)的数据进行整合。来自多源的数据整合会增强 NLP 应用的有效性与功能性。

下面的 Listing 2-3 演示了如何创建一个示例文件,并用该文件做数据抽取。我们将使用 python-docx 库对 Word 文档进行写入与读取。

2.3.1 从 MS Word 文件提取数据

创建示例文件。

# Install python-docx if you haven't done it already.
# I am not including the output of this code due to space constraints.
!pip install python-docx

下面脚本创建了一个包含标题、多段文字、无序列表与表格的示例 Word 文档。

from docx import Document
from docx.shared import Pt
# Create a new blank Document.
doc = Document()
# Add a title
doc.add_heading('Sample Document For NLP Analysis', level=1)
# Add a couple of paragraphs.
doc.add_paragraph('This sample Word demo document contains multiple paragraphs.')
doc.add_paragraph('Here is another paragraph with more text.')
# Add few bullet points.
doc.add_paragraph('Sample bullet 1', style='List Bullet')
doc.add_paragraph('Sample bullet 2', style='List Bullet')
doc.add_paragraph('Sample bullet 3', style='List Bullet')
# Add a table for demo.
table = doc.add_table(rows=3, cols=2)
table.style = 'Table Grid'
# Add header row
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Header Sample 1'
hdr_cells[1].text = 'Header Sample 2'
# Add a couple of data rows
row_cells = table.rows[1].cells
row_cells[0].text = 'Sample Row 1'
row_cells[1].text = 'Data Point 1'
row_cells = table.rows[2].cells
row_cells[0].text = 'Sample Row 1'
row_cells[1].text = 'Data Point 2'
# Save the newly created document.
doc.save('NLP_demo_sample_file.docx')

下面脚本加载该 Word 文档,提取并打印文档中的各种元素,如标题、段落、无序列表和表格数据。

from docx import Document
# First load the Word document created above.
doc = Document('NLP_demo_sample_file.docx')
# Extract and print the title
# Assume it to be the opening paragraph.
print(f"Title: {doc.paragraphs[0].text}")
# Extract and print all paragraphs.
print("\nParagraphs:")
for para in doc.paragraphs:
    print(para.text)
# Extract and print bullet points (assuming they are in a list)
print("\nBullet Points:")
for para in doc.paragraphs:
    if para.style.name == 'List Bullet':
        print(para.text)
# Extract and print table data
print("\nTable Data:")
for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            print(cell.text, end=' | ')
        print()

示例输出(Listing 2-3):

Title: Sample Document For NLP Analysis
Paragraphs:
Sample Document For NLP Analysis
This sample Word demo document contains multiple paragraphs.
Here is another paragraph with more text.
Sample bullet 1
Sample bullet 2
Sample bullet 3
Bullet Points:
Sample bullet 1
Sample bullet 2
Sample bullet 3
Table Data:
Header Sample 1 | Header Sample 2 |
Sample Row 1 | Data Point 1 |
Sample Row 1 | Data Point 2 |

(Listing 2-3:从 MS Word 文件提取数据)

2.4 从 HTML 提取数据

大量结构化与非结构化文本以 HTML 文档形式存在。网站、博客与在线文章通常以 HTML 格式发布,因此 HTML 文档是提取现实语言使用与模式的重要原始来源。解析 HTML 文本可以访问到丰富且多样的文本数据,这对训练 NLP 模型至关重要。

HTML 文档的结构化特性使得提取合适信息相对容易。HTML 的内在元数据(如标签与属性,例如 <title><h1><p>)为文本提供了额外背景信息。HTML 文档通常包含超链接,这也便于跨站点爬取与探索。Listing 2-4 先创建一个示例 HTML 文件用于演示,然后给出注释良好的代码来提取该 HTML 文档的各个元素。图 2-2 展示了使用 Beautiful Soup 提取 HTML 文本的流程。

image.png (图 2-2:使用 Beautiful Soup 从 HTML 提取文本的流程)

2.4.1 从 HTML 文档提取数据

首先,创建一个 HTML 文档用于后续提取(见 Listing 2-4)。要充分利用本节内容,建议具备基本的 HTML 知识。

# Import the BeautifulSoup class from the bs4 library
from bs4 import BeautifulSoup
# The following code reads the HTML file.
# Open 'Sample.html' in read mode.
with open('my_sample.html', 'r') as file:
    html = file.read()  # Read the content of the file into the 'html' variable
# Parse the HTML content using BeautifulSoup.
soup = BeautifulSoup(html, 'html.parser')
# Extract the text of the <title> element.
title = soup.title.string
# Extract the text of the <h1> element within the <header>.
main_heading = soup.header.h1.string
# Extract all href attributes from <a> elements within the <nav>.
nav_links = [a['href'] for a in soup.nav.find_all('a')]
# Extract the text of the <p> element.
home_section = soup.find(id="home").p.string
# Extract the text of the <p> element within the section with id="about".
about_section = soup.find(id="about").p.string
# Extract the text of the <p> element within the section with id="contact".
contact_section = soup.find(id="contact").p.string
# Extract the href attribute of the <a> element.
contact_email = soup.find(id="contact").a['href']
# Extract the text of the <p> element within the <footer>.
footer_text = soup.footer.p.string
# Print the title.
print("Title:", title)
# Print the main heading.
print("Main Heading:", main_heading)
# Print navigation links.
print("Navigation Links:", nav_links)
# Print the text of the home section.
print("Home Section:", home_section)
# Print the contents of the about section.
print("About Section:", about_section)
# Print the contents of the contact section.
print("Contact Section:", contact_section)
# Print the contact email link.
print("Contact Email:", contact_email)
# Print the footer text.
print("Footer Text:", footer_text)

示例输出:

Title: Sample HTML File
Main Heading: Main Title
Navigation Links: ['#home', '#about', '#contact']
Home Section: Welcome home. Can we have a coffee?.
About Section: This section writes about an overview of my website.
Contact Section: None
Contact Email: mailto:my_name@my_email.com
Footer Text: © I am writing a book with my copyright on it.

(Listing 2-4:使用 Beautiful Soup 从 HTML 文档提取数据)

你可以将下面的 HTML 内容保存为文件并运行上述提取代码进行测试:

# Create an HTML document as said.
html_content = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample HTML File</title>
</head>
<body>
    <header>
        <h1>Main Title</h1>
        <nav>
            <ul>
                <li><a href="#home">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>
    <section id="home">
        <h2>Home Section</h2>
        <p>Welcome home. Can we have a coffee?.</p>
    </section>
    <section id="about">
        <h2>About Section</h2>
        <p>This section writes about an overview of my website.</p>
    </section>
    <section id="contact">
        <h2>Contact Section</h2>
    <p>You can contact me using my personal email id<a href="mailto:my_name@my_email.com">info@example.com</a>.</p>
    </section>
    <footer>
        <p>&copy; I am writing a book with my copyright on it.</p>
    </footer>
</body>
</html>
'''
# Save the HTML content to a file
with open('my_sample.html', 'w') as file:
    file.write(html_content)

Beautiful Soup 是一个流行的 Python 库,用于从网页抓取并解析数据。建议你尝试上述代码片段并对其它 HTML 文档进行实验,以熟悉不同标签与结构下的文本抽取方法。

2.5 从 JSON 提取数据

与 HTML 文本类似,JSON 文件也提供了一种用于存储与交换数据的结构化格式。JSON(JavaScript Object Notation)文件体积轻、易解析,使其成为处理 NLP 项目中典型的大型数据集的近乎理想选择。JSON 文件具有嵌套结构,能较为方便地支持复杂的数据表示,便于组织文本、文本注释及其元数据。正因为这些特性,JSON 在文本预处理与分析中通常是优先选项。

下面我们先创建一个示例 JSON 文件,然后给出用于提取数据的注释良好的代码示例。

2.5.1 从 JSON 文件提取数据

首先,创建将用于之后提取文本的 JSON(见 Listing 2-5)。要充分利用本节内容,建议具备 JSON 基本知识。

import json # import the required Python library to create the JASON file.
# Let's create a sample dictionary with some data.
data = {
    "title": "Sample JSON File",
    "description": "This is a sample JSON file containing various elements.",
    "sections": [
        {
            "heading": "Introduction to the World of JASON",
            "content": "This is your introduction to the content of a sample JSON file."
        },
        {
            "heading": "Details of JASON",
            "content": "Put your details about the JSON file content here."
        },
        {
            "heading": "Conclusion",
            "content": "Put your concluding remarks here."
        }
    ],
    "footer": "Put your footer text here."
}
# Save the sample JSON file,
with open('sample_jason.json', 'w') as file:
    json.dump(data, file, indent=4)

(Listing 2-5:从 JSON 文件提取数据)

现在我们来读取并提取其内容。

import json # Import json.
# Read the JSON file.
with open('sample_jason.json', 'r') as file:  # Open the JASON file in read mode.
    data = json.load(file)  # Load the JSON file into the 'data' variable.
# Extract various elements.
title = data["title"]  # Extract "title".
description = data["description"]  # Extract "description".
sections = data["sections"]  # Extract "sections".
footer = data["footer"]  # Extract "footer".
# Print the extracted text data.
print("Title:", title)  # Print the title.
print("Description:", description)  # Print the description.
for section in sections:  # Loop through the sections list.
    print(f"Section Heading: {section['heading']}")  # Print the section heading.
    print(f"Section Content: {section['content']}")  # Print the section content.
print("Footer:", footer)  # Print the footer text.

示例输出:

Title: Sample JSON File
Description: This is a sample JSON file containing various elements.
Section Heading: Introduction to the World of JASON
Section Content: This is your introduction to the content of a sample JSON file.
Section Heading: Details of JASON
Section Content: Put your details about the JSON file content here.
Section Heading: Conclusion
Section Content: Put your concluding remarks here.
Footer: Put your footer text here.

2.6 从 PDF 提取数据

PDF 文件常用于分发与归档文档,通常包含一致格式的富文本内容。PDF 文本中常包含结构化文本、图像以及可用于后续文本抽取与分析的元数据。几乎所有业务领域(包括金融、法律与学术)都会依赖 PDF 格式的文件,因此它们是许多 NLP 任务的重要数据源。图 2-3 给出了从 PDF 文件提取文本数据的简化示意。

image.png

(图 2-3:来自 PDF 的文本数据提取示意)

2.6.1 从 PDF 提取数据(示例)

首先,我们为后续文本抽取创建一个小的 PDF 文件(见 Listing 2-6)。本节示例将演示如何创建 PDF(使用 reportlab),以及如何用 PyPDF2(或其他库)提取文本。

# Install reportlab module if you have not done it already.
# I am not including this code's output here for space reasons.
!pip install reportlab
# Let's create a small PDF demo file as said.
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
# Create a demo PDF file,
file_path = "sample_pdf.pdf"
c = canvas.Canvas(file_path, pagesize=letter)
c.drawString(100, 750, "Title: Demo PDF")
c.drawString(100, 735, "This is a demo PDF document.")
c.drawString(100, 720, "Section 1: Introduction")
c.drawString(100, 705, "Put your introductory text here.")
c.drawString(100, 690, "Section 2: Details")
c.drawString(100, 675, "Put the details of the PDF document.")
c.drawString(100, 660, "Section 3: Conclusion")
c.drawString(100, 645, "The conclusion text in this section.")
c.save()

接着,使用 PyPDF2 提取 PDF 文本:

# To extract the PDF text install fitz if not done already.
# This code's output not included here.
!pip install PyPDF2
import PyPDF2
# Open the PDF file
file_path = "sample_pdf.pdf"
with open(file_path, 'rb') as file:
    reader = PyPDF2.PdfReader(file)
    number_of_pages = len(reader.pages)
    text = ""
    for page_number in range(number_of_pages):
        page = reader.pages[page_number]
        text += page.extract_text()
print("Extracted Text:")
print(text)

示例输出:

Extracted Text:
Title: Demo PDF
This is a demo PDF document.
Section 1: Introduction
Put your introductory text here.
Section 2: Details
Put the details of the PDF document.
Section 3: Conclusion
The conclusion text in this section.

(Listing 2-6:从 PDF 提取数据)

注:除了 PyPDF2 外,实际项目中常用的 PDF 抽取工具还有 PyMuPDF(fitz)、pdfminer.six、camelot(用于表格)、tabula-py(用于表格)等;针对扫描件/图片型 PDF,通常需要先做 OCR(例如用 Tesseract)。

2.7 网页爬取(Web Scraping)

网页爬取使我们能够从万维网大规模收集文本数据。这些数据是训练与评估 NLP 模型的重要来源。研究人员与工程师可以利用多样化来源构建丰富数据集,从而提升模型对多语言、多语境与多主题的理解能力。

万维网可以提供最新的实时信息。这种动态数据对于构建更准确、更具时效性的 NLP 应用非常关键,因为它能反映当前的语言使用与新兴趋势。Listing 2-7 给出了如何从任意网页 URL 抓取数据的简单示例。图 2-4 描述了通用网页爬取流程。

image.png (图 2-4:网页爬取流程示意)

2.7.1 在 NLP 任务中的网页爬取示例

import requests
from bs4 import BeautifulSoup
# URL of the webpage to scrape.
url = 'https://en.wikipedia.org/wiki/Blog'  # Inserting a random URL.
# Send a GET request to the URL
response = requests.get(url)
# Parse the HTML content of the scrapped page.
soup = BeautifulSoup(response.content, 'html.parser')
# Extract text data.
text_data = ''
for paragraph in soup.find_all('p'):
    text_data += paragraph.get_text() + '\n'
print('Scraped Text Data:')
print(text_data)

示例输出(仅显示首段):

A blog (a truncation of "weblog")[1] is an informational website consisting of discrete, often informal diary-style text entries (posts). Posts are typically displayed in reverse chronological order so that the most recent post appears first, at the top of the web page. In the 2000s, blogs were often the work of a single individual, occasionally of a small group, and often covered a single subject or topic. In the 2010s, "multi-author blogs" (MABs) emerged, featuring the writing of multiple authors and sometimes professionally edited. MABs from newspapers, other media outlets, universities, think tanks, advocacy groups, and similar institutions account for an increasing quantity of blog traffic. The rise of Twitter and other "microblogging" systems helps integrate MABs and single-author blogs into the news media. Blog can also be used as a verb, meaning to maintain or add content to a blog.
Continued...

(Listing 2-7:在 NLP 任务中的网页爬取示例)

注意与合规提醒:在进行网页抓取时,请务必遵守目标网站的 robots.txt、服务条款与法律法规;合理设置请求速率、并尊重版权与隐私;对大规模抓取建议使用 API(若网站提供)或事先取得许可,以避免法律与伦理风险。

2.8 关键概念回顾

NLP(自然语言处理)是分析与理解大量文本数据的一种极具影响力的工具,而这类数据在各个业务领域中都大量存在。使用现代 NLP 技术进行文本分析可以揭示模式、趋势与洞见,从而在商业、法律、社交媒体等各个领域支持以数据为驱动的决策。

在任何 NLP 项目中,找到质量与数量都合适的数据是最具挑战性的任务之一。本章讨论了各种文本数据来源(语料库),并演示了如何从这些来源中提取有意义的数据。本章只是为任何 NLP 从业者提供的起点;关于获取高质量数据还有许多更详尽、进阶的技术可供学习。若需更多信息,互联网资源与标准的 NLP 教科书是最好的参考来源。网页爬取(web scraping)是非常重要的流程之一,因为许多大规模 AI(即生成式 AI,GenAI)项目将其作为训练大规模 NLP 模型的主要数据来源。

本章还讨论了其它获取高质量数据的技术,以及如何从 Word 文件、HTML 文档、JSON 文件和 PDF 中提取文本数据。我们注意到,每种格式需要不同的方法才能把数据转换为可用格式。掌握这些技术对每位 NLP 工程师都很重要,因为这是他们可能参与的任何 NLP 项目的起点。

2.9 练习题

访问 NLTK 附带的 Gutenberg 文本语料库。列出其中包含的所有书名,并任选两本练习文本抽取与摘要。

创建一个包含若干段落文本的示例 Microsoft Word 文档。使用合适的 Python 库提取文本并打印其内容。

将练习 2 的所有步骤针对一个 HTML 文件重复一遍。

练习从实时 JSON 文件和真实网页 URL 中抽取数据。

2.10 参考文献

  1. www.oreilly.com/api/v2/epub…. 最后访问:2024 年 7 月 29 日。
  2. Datacamp (2023). NLTK Sentiment Analysis Tutorial for Beginners. Available at: www.datacamp.com/tutorial/te…
  3. nltk.org (2019). Accessing Text Corpora and Lexical Resources. Available at: www.nltk.org/book/ch02.h…. 最后访问:2024 年 7 月 30 日。
  4. Tripathi, S. (2023). How to parse HTML in Python with PyQuery or Beautiful Soup. Available at: blog.apify.com/how-to-pars…. 最后访问:2024 年 7 月 30 日。
  5. Timalsina, A. (2024). How to extract data from a PDF. Available at: www.docsumo.com/blog/extrac…. 最后访问:2024 年 7 月 30 日。
  6. kinsta.com (2022). What Is Web Scraping? How To Legally Extract Web Content. Available at: kinsta.com/knowledgeba…. 最后访问:2024 年 7 月 30 日。