6 文本清理——从零学NLP系列教程
在上篇的内容中,我们对NLP(自然语言处理)的基本概念和各种技术进行了概述,为了更好地进入NLP的世界,理解文本预处理是至关重要的一步。本篇文章将专注于文本预处理中的一个重要环节——文本清理。文本清理是为后续分词、特征提取和模型训练打下基础的关键步骤。
什么是文本清理?
文本清理的目的是通过去除不必要的字符、标点、不相关的信息等,使得文本更为干净和一致。这个过程通常涉及多个步骤,以下是常见的文本清理步骤:
- 去除HTML标签
- 去除标点符号和特殊字符
- 小写化处理
- 去除停用词
- 词干提取与词形还原
1. 去除HTML标签
在处理网页抓取的数据时,常常会出现HTML标签。为了提取纯文本,我们需要去除这些标签。可以使用正则表达式来实现这一点。
import re
def remove_html_tags(text):
"""
去除HTML标签
"""
clean_text = re.sub(r'<.*?>', '', text)
return clean_text
# 示例
sample_html = "<p>Hello, this is a <b>test</b>.</p>"
print(remove_html_tags(sample_html)) # 输出: "Hello, this is a test."
2. 去除标点符号和特殊字符
除了HTML标签,文本中可能还包含许多标点和特殊字符,这些在大多数NLP任务中都是无用的。
def remove_punctuation(text):
"""
去除文本中的标点符号
"""
return re.sub(r'[^\w\s]', '', text)
# 示例
sample_text = "Hello, world! This is a test: #NLP."
print(remove_punctuation(sample_text)) # 输出: "Hello world This is a test NLP"
3. 小写化处理
将文本统一转为小写,有助于减少词汇的多样性。例如,"Apple"
和"apple"
应当被视作同一词。
def lowercase_text(text):
"""
将文本转为小写
"""
return text.lower()
# 示例
print(lowercase_text("Hello World!")) # 输出: "hello world!"
4. 去除停用词
停用词是指在文本中经常出现但对大部分任务没有实际意义的词,例如“的”、“是”、“在”等。去除停用词有助于减少噪声。
from nltk.corpus import stopwords
# 确保下载停用词库
import nltk
nltk.download('stopwords')
def remove_stopwords(text):
"""
去除停用词
"""
stop_words = set(stopwords.words('english'))
word_tokens = text.split()
return ' '.join([word for word in word_tokens if word not in stop_words])
# 示例
sample_text = "This is a test sentence for NLP."
print(remove_stopwords(sample_text)) # 输出: "test sentence NLP."
5. 词干提取与词形还原
词干提取和词形还原旨在将词汇归一化,减少其派生形式。例如,"running"
、"ran"
和"runs"
可能都被归为"run"
。
词干提取
使用NLTK中的PorterStemmer
进行词干提取。
from nltk.stem import PorterStemmer
def stemming(text):
"""
词干提取
"""
ps = PorterStemmer()
word_tokens = text.split()
return ' '.join([ps.stem(word) for word in word_tokens])
# 示例
sample_text = "running runner ran"
print(stemming(sample_text)) # 输出: "run run ran"
词形还原
词形还原被认为是更加高级的归一化技术,利用上下文信息将词还原为其基本形式。
from nltk.stem import WordNetLemmatizer
# 确保下载WordNet库
nltk.download('wordnet')
def lemmatization(text):
"""
词形还原
"""
lemmatizer = WordNetLemmatizer()
word_tokens = text.split()
return ' '.join([lemmatizer.lemmatize(word) for word in word_tokens])
# 示例
sample_text = "running ran"
print(lemmatization(sample_text)) # 输出: "running ran" (仅在更复杂的文本中有所不同)
小结
通过以上步骤,我们能够对文本数据进行有效的清理。这为后续的分词、特征提取奠定了良好的基础。记住,文本清理并不是固定的步骤,具体的应用场景可能会要求我们根据需要选择性地执行这些步骤。
接下来,我们将进入文本预处理的另一个重要部分——分词。分词是将清理后的文本分割为单独的词语,这一过程对于后续的模型训练和特征提取至关重要。请继续关注!