首页 > 解决方案 > 如何在 Python 中创建一个词袋

问题描述

清理并标记化后的数据框测试。

from nltk.tokenize import TweetTokenizer
tt = TweetTokenizer()
test['tokenize'] = test['tweet'].apply(tt.tokenize)
print(test)

输出

0  congratulations dear friend ... [congratulations, dear, friend]
1  happy anniversary be happy  ... [happy, anniversary, be, happy]
2  make some sandwich          ...          [make, some, sandwich]

我想为我的数据创建一个词袋。以下给了我错误:'list'对象没有属性'lower'

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()

BOW = vectorizer.fit_transform(test['tokenize'])
print(BOW.toarray())
print(vectorizer.get_feature_names())

第二个:AttributeError: 'list' object has no attribute 'split'

from collections import Counter
test['BOW'] = test['tokenize'].apply(lambda x: Counter(x.split(" ")))
print(test['BOW'])

你能帮我一种方法或两种方法吗?谢谢!

标签: pythonnltk

解决方案


vectorizer.fit_transform将 str、unicode 或文件对象的可迭代对象作为参数。您已经传递了一个可迭代的列表(标记化字符串)。您可以只传递原始字符串集,test['tweet']因为 CountVectorizer 会为您进行标记化。

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
BOW = vectorizer.fit_transform(test['tweet'])
print(BOW.toarray())
print(vectorizer.get_feature_names())

这应该会给你预期的输出。


推荐阅读