如何在 Python 中创建词袋
How to create a bag of word in Python
Dataframe test 在我清理并标记化它之后。
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' object has no attribute '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'对象没有属性'split'
from collections import Counter
test['BOW'] = test['tokenize'].apply(lambda x: Counter(x.split(" ")))
print(test['BOW'])
能否请您协助我使用其中一种方法或两种方法。谢谢!
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())
这应该会给你预期的输出。
根据您的输出示例,test['tokenize'] 包含单元格中的列表。这些列表是通过“”拆分从字符串中检索到的值,因此要使这一行 test['BOW'] = test['tokenize'].apply(lambda x: Counter(x.split(" ")))
正常工作,请尝试将其更改为 test['BOW'] = test['tokenize'].apply(lambda x: Counter(x))
Dataframe test 在我清理并标记化它之后。
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' object has no attribute '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'对象没有属性'split'
from collections import Counter
test['BOW'] = test['tokenize'].apply(lambda x: Counter(x.split(" ")))
print(test['BOW'])
能否请您协助我使用其中一种方法或两种方法。谢谢!
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())
这应该会给你预期的输出。
根据您的输出示例,test['tokenize'] 包含单元格中的列表。这些列表是通过“”拆分从字符串中检索到的值,因此要使这一行 test['BOW'] = test['tokenize'].apply(lambda x: Counter(x.split(" ")))
正常工作,请尝试将其更改为 test['BOW'] = test['tokenize'].apply(lambda x: Counter(x))