我正在使用 CountVectorizer
获取字符串列表中的单词列表
from sklearn.feature_extraction.text import CountVectorizer
raw_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 CountVectorizer
raw_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]]
关于python - 在 sklearn 中将一个句子映射到它的词汇表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55182833/