我正在使用CountVectorizer
来获取字符串列表中的单词列表
from sklearn.feature_extraction.text import CountVectorizerraw_text = [ 'The dog hates the black cat', 'The black dog is good']raw_text = [x.lower() for x in raw_text]vocabulary = vectorizer.vocabulary_ vocabulary = dict((v, k) for k, v in vocabulary.iteritems())vocabulary
在词汇表中,我得到了以下正确的数据
{0: u'black', 1: u'cat', 2: u'dog', 3: u'good', 4: u'hates', 5: u'is', 6: u'the'}
现在我希望得到原始句子“映射”到这些新值的结果,像这样:
expected_output = [ [6, 2, 4, 6, 0, 1], [6, 0, 2, 5, 3]]
我尝试查阅了Sklearn的文档,但找不到任何似乎能完成这个操作的内容,我甚至不知道我试图执行的操作的正确术语,所以在Google上也找不到任何结果。
有什么方法可以实现这个结果吗?
回答:
像这样查找每个单词:
from sklearn.feature_extraction.text import CountVectorizerraw_text = [ 'The dog hates the black cat', 'The black dog is good']cv = CountVectorizer()cv.fit_transform(raw_text)vocab = cv.vocabulary_.copy()def lookup_key(string): s = string.lower() return [vocab[w] for w in s.split()]list(map(lookup_key, raw_text))
输出:
[[6, 2, 4, 6, 0, 1], [6, 0, 2, 5, 3]]