TfidfVectorizer、CountVectorizer 和 TfidfTransformer 是 sklearn 中处理自然语言常用的工具。TfidfVectorizer 相当于 CountVectorizer + TfidfTransformer。
下面先说 CountVectorizer。
CountVectorizer
CountVectorizer 的作用是将文本文档转换为计数的稀疏矩阵。下面举一个具体的例子来说明(代码来自于官方文档)。
from sklearn.feature_extraction.text import CountVectorizer
# 定义一个 list,其中每个元素是一个文档(一个句子)
corpus = [
'This is the first document.',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
]
vectorizer = CountVectorizer()
# 将文本数据转换为计数的稀疏矩阵
X = vectorizer.fit_transform(corpus)
# 查看每个单词的位置
print(vectorizer.get_feature_names())
#输出为 ['and', 'document', 'first', 'is',