处理文本数据通常涉及多个步骤,包括文本清洗、分词、去除停用词等,是NLP的基础工作。
1、文本清洗
文本清洗包括去除特殊字符、转换为小写、处理缩写等。
标准化则可能包括拼写纠正和词形还原。
import re # 正则
import nltk # 自然语言处理包
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
# 数据包加载成功
nltk.download('XXX')
# 转换为小写
text = text.lower()
# 去除特殊字符和数字
text = re.sub(r'[^a-zA-Z\s]', '', text)
# 分词
tokens = word_tokenize(text)
# 去除停用词
stop_words = set(stopwords.words('english'))
tokens = [token for token in tokens if token not in stop_words]
# 词形还原
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(token) for token in tokens]
text = ' '.join(tokens)
2、词袋模型(Bag of Words)和和TF-IDF(Term Frequency-Inverse Document Frequency)
词袋模型和TF-IDF是文本分析中常用的两种方法,用于将文本数据转换为数值形式,以便进行机器学习建模。
2.1 词袋模型
词袋模型是一种简单的文本表示方法,它将文本转换为一个长向量,其中每个维度对应一个唯一的单词,向量的值表示该单词在文本中出现的频率。
代码示例
from sklearn.feature_extraction.text import CountVectorizer
# 示例文本
texts = [
"The quick brown fox jumps over the lazy dog",
"I love watching the quick brown fox",
"The dog was lazy and the fox was quick"
]
# 创建词袋模型
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
# 查看特征名称
print(vectorizer.get_feature_names_out())
# 查看词袋模型矩阵
print(X.toarray())
2.2 TF-IDF
TF-IDF 是一种改进的词袋模型,它不仅考虑单词在单个文档中的频率(TF),还考虑单词在整个文档集合中的稀有程度(IDF)。TF-IDF 值越高,表示单词在文档中越重要。
代码示例
from sklearn.feature_extraction.text import TfidfVectorizer
# 示例文本
texts = [
"The quick brown fox jumps over the lazy dog",
"I love watching the quick brown fox",
"The dog was lazy and the fox was quick"
]
# 创建TF-IDF模型
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)
# 查看特征名称
print(vectorizer.get_feature_names_out())
# 查看TF-IDF矩阵
print(X.toarray())