
处理文本数据
|
255
7.3.1
将词袋应用于玩具数据集
词袋表示是在 CountVectorizer 中实现的,它是一个变换器(
transformer
)。我们首先将它
应用于一个包含两个样本的玩具数据集,来看一下它的工作原理:
In[7]:
bards_words =["The fool doth think he is wise,",
"but the wise man knows himself to be a fool"]
我们导入 CountVectorizer 并将其实例化,然后对玩具数据进行拟合,如下所示:
In[8]:
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer()
vect.fit(bards_words)
拟合
CountVectorizer
包括训练数据的分词与词表的构建,我们可以通过
vocabulary_
属性
来访问词表:
In[9]:
print("Vocabulary size: {}".format(len(vect.vocabulary_)))
print("Vocabulary content:\n {}".format(vect.vocabulary_))
Out[9]:
Vocabulary size: 13
Vocabulary content:
{'the': 9, 'himself': 5, 'wise': 12, 'he': 4, 'doth': ...