python - 如何在 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'])
你能帮我一种方法或两种方法吗?谢谢!
解决方案
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())
这应该会给你预期的输出。
推荐阅读
- python - 我可以将 F() 表达式值传递给我自己的函数并仍然在 Django 中调用更新吗?
- python - 在我的算法运行良好后,我的数组返回全零
- android - 在 Godot 中制作的 android 应用程序的签名密钥
- .net-core - .NET Core 3.1 上的 Azure Functions 3 抛出 OutOfMemoryException
- python - docker中的python3 mayavi没有安装
- mysql - 协助在不使用实际数据的情况下向表中添加记录
- java - 有没有办法在另一个方法中使用一个方法的返回值?
- mongodb - Mongo 搜索数组,在 $or 中只有一个匹配项
- javascript - attributeList.push() 在 cognito 中不起作用
- reverse-engineering - 运行 AFL-Fuzzer 缓冲区溢出