首页 > 解决方案 > CountVectorizer 假设将数据集转换为稀疏矩阵,但它没有这样做

问题描述

我正在努力学习 NLP。所以首先我创建了一个函数,它可以从字符串中提取非停用词并创建这些词的列表。我已经事先从 nltk 下载 shell 下载了停用词列表

import pandas as pd
msg=pd.read_csv('SMSSpamCollection',sep='\t',names=['label','message'])
msg['msg_len']=msg.message.apply(len)
from nltk.corpus import stopwords

import string

def cleantext(text):
    nopunc=[c for c in text if c not in string.punctuation]
    nopunc=''.join(nopunc)
    clean_text=[w for w in nopunc.split() if w.lower()
                not in stopwords.words('english')]
    return clean_text

该功能工作正常。然后应用 CountVectorizer 以从单词列表 clean_text 中创建稀疏矩阵

from sklearn.feature_extraction.text import CountVectorizer
bow=CountVectorizer(analyzer=cleantext).fit(msg['message'])
print(len(bow))

当尝试使用 len() 打印长度时,它给了我一个错误 TypeError: object of type 'CountVectorizer' has no len()

所以我尝试打印它,看看它到底是什么,我把它作为我的输出 - CountVectorizer(analyzer=<function cleantext at 0x0000026F6D736280>)

这里有什么问题?

标签: pythonmachine-learningscikit-learnnlpnltk

解决方案


推荐阅读