在sklearn中将句子映射到其词汇表

时间:2019-03-15 12:39:12

标签: python python-3.x python-2.7 machine-learning scikit-learn

我正在使用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中找不到任何结果。

有什么办法可以达到这个结果?

3 个答案:

答案 0 :(得分:3)

按如下方式查找每个单词:

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]]

答案 1 :(得分:2)

您可以尝试以下方法吗?

mydict = {0: u'black', 1: u'cat', 2: u'dog',
          3: u'good', 4: u'hates', 5: u'is', 6: u'the'}


def get_val_key(val):
    return list(mydict.keys())[list(mydict.values()).index(val.lower())]


raw_text = [
    'The dog hates the black cat',
    'The black dog is good'
]
expected_output = [list(map(get_val_key, text.split())) for text in raw_text]
print(expected_output)

输出:

[[6, 2, 4, 6, 0, 1], [6, 0, 2, 5, 3]]

答案 2 :(得分:1)

我认为您可以只适合文本内容来构建词汇表,然后使用build_analyzer()

来使用词汇表创建所需的映射
from sklearn.feature_extraction.text import CountVectorizer
raw_text = [
    'The dog hates the black cat',
    'The black dog is good'
]
vectorizer = CountVectorizer()
vectorizer.fit(raw_text)

analyzer = vectorizer.build_analyzer()
[[vectorizer.vocabulary_[i]  for i in analyzer(doc)]  for doc in raw_text]

输出:

  

[[6,2,4,6,0,1],[6,0,2,5,5]]