首页 > 解决方案 > NLP:将 CountVectorizer 应用于包含特征列表的列

问题描述

我想申请CountVectorizer包含单词和短语列表的列。换句话说,语料库不是一个字符串,而是一个列表。问题是CountVectorizer我遇到的任何其他相关函数都需要一个字符串作为输入。将列表加入一个字符串并进行标记是没有意义的,因为某些短语包含 2 个单词。有任何想法吗?

例子:

ID      corpus
1       ["Harry Potter","Batman"]
2       ["Batman", "Superman", "Lord of the Rings"]

期望的结果:

ID   Harry Potter    Batman    Superman    Lord of the Rings
1    1               1         0           0
2    0               1         1           1

标签: pythonscikit-learnnlpcountvectorizer

解决方案


由于您已经对句子进行了标记,CountVectorizer因此可能不需要这样做。

我在MultiLabelCounter() 这里写了一个,可以解决你的问题。

import pandas as pd
x = [["Harry Potter","Batman"], ["Batman", "Superman", "Lord of the Rings"]]

mlc = MultiLabelCounter()
mlc.fit_transform(x)
# [[1, 1, 0, 0], [1, 0, 1, 1]]

mlc.classes_
# ['Batman', 'Harry Potter', 'Lord of the Rings', 'Superman']

在此处输入图像描述


推荐阅读