python - 在 sklearn 中将一个句子映射到它的词汇表

标签 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 中找到任何结果。

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

最佳答案

像这样查找每个单词:

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/

相关文章:

python - 遍历 Django 模板中的一个列表

html - 如何使用Selenium和webdriver提取部分网页源代码?

Django 自定义 PasswordResetForm

python - python 2.7中列表索引超出范围

python - Python 中的线程 block Main

python - 在 Python 3 上是否有任何库可以重新启动脚本?

python - 如何使用列表理解构建字典?

python - tkinter - wm 协议(protocol)不处理 WM_HELP 消息

python - ImportError : Missing required dependencies ['numpy' ]. 没有任何帮助

python - pymongo 数据库的 insert() 和 insert_one() 方法都不能调用“Collection”对象