Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-从标记列表到单词包_Python_Pandas_Scikit Learn_Nlp_Nltk - Fatal编程技术网

Python-从标记列表到单词包

Python-从标记列表到单词包,python,pandas,scikit-learn,nlp,nltk,Python,Pandas,Scikit Learn,Nlp,Nltk,我正在努力处理一大堆文字。我有一个带有文本列的pandas数据框架,我正确地标记、删除停止词和词干。 最后,对于每个文档,我都有一个字符串列表 我的最终目标是为本专栏计算单词包,我已经看到scikit learn有一个函数可以做到这一点,但它对字符串有效,而不是对字符串列表有效 我自己用NLTK做预处理,希望保持这种方式 有没有一种方法可以根据标记列表计算单词包?e、 例如: ["hello", "world"] ["hello", "stackoverflow", "hello"] 应转换为

我正在努力处理一大堆文字。我有一个带有文本列的pandas数据框架,我正确地标记、删除停止词和词干。 最后,对于每个文档,我都有一个字符串列表

我的最终目标是为本专栏计算单词包,我已经看到scikit learn有一个函数可以做到这一点,但它对字符串有效,而不是对字符串列表有效

我自己用NLTK做预处理,希望保持这种方式

有没有一种方法可以根据标记列表计算单词包?e、 例如:

["hello", "world"]
["hello", "stackoverflow", "hello"]
应转换为

[1, 1, 0]
[2, 0, 1]
词汇:

["hello", "world", "stackoverflow"]

您可以通过使用
计数器进行过滤来创建
数据帧
,然后转换为
列表
s:

from collections import Counter

df = pd.DataFrame({'text':[["hello", "world"],
                           ["hello", "stackoverflow", "hello"]]})

L = ["hello", "world", "stackoverflow"]

f = lambda x: Counter([y for y in x if y in L])
df['new'] = (pd.DataFrame(df['text'].apply(f).values.tolist())
               .fillna(0)
               .astype(int)
               .reindex(columns=L)
               .values
               .tolist())
print (df)

                            text        new
0                 [hello, world]  [1, 1, 0]
1  [hello, stackoverflow, hello]  [2, 0, 1]

sklearn.feature\u extraction.text.CountVectorizer可以帮助很多。以下是官方文件的例子:

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
corpus = [
    'This is the first document.',
    'This is the second second document.',
    'And the third one.',
    'Is this the first document?',
]
X = vectorizer.fit_transform(corpus)
X.toarray() 
/*array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
   [0, 1, 0, 1, 0, 2, 1, 0, 1],
   [1, 0, 0, 0, 1, 0, 1, 1, 0],
   [0, 1, 1, 1, 0, 0, 1, 0, 1]]...)*/
您可以使用方法vectorizer获取要素名称。使用sklearn.feature\u extraction.text.CountVectorizer获取要素名称() 输出:

['hello', 'stackoverflow', 'world']

[[1 0 1]
 [2 1 0]]

你找到解决办法了吗?副本
['hello', 'stackoverflow', 'world']

[[1 0 1]
 [2 1 0]]