假设我需要对以下数据应用 CountVectorizer():
words = [ 'A am is', 'This the a', 'the am is', 'this a am',]
我做了以下操作:
from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer()X = vectorizer.fit_transform(corpus)print(X.toarray())
它返回以下结果:
[[1 1 0 0] [0 0 1 1] [1 1 1 0] [1 0 0 1]]
作为参考,print(vectorizer.get_feature_names())
输出 ['am', 'is', 'the', 'this']
为什么 ‘a’ 没有被读取?
是否是因为单个字母的单词在 CountVectorizer() 中不被视为单词?
回答:
查看 文档
token_pattern
表示什么构成“token”的正则表达式,仅在 analyzer == ‘word’ 时使用。默认的正则表达式选择 2 个或更多字母数字字符的 token(标点符号被完全忽略,并始终被视为 token 分隔符)。
默认的 tokenizer 忽略所有单字符 token。这就是为什么 a
缺失的原因。
如果你希望单字符 token 包含在词汇表中,那么你需要使用自定义 tokenizer。
示例代码
from sklearn.feature_extraction.text import CountVectorizervectorizer = CountVectorizer(tokenizer=lambda txt: txt.split())X = vectorizer.fit_transform(words)print (vectorizer.get_feature_names())
输出:
['a', 'am', 'is', 'the', 'this']