AttributeError:“ list”对象在TF-IDF

时间:2019-06-24 11:25:33

标签: python pandas tf-idf countvectorizer

我正在尝试在熊猫列中应用TF-IDF

数据

    all_cols
0   who is your hero and why
1   what do you do to relax
2   this is a hero
4   how many hours of sleep do you get a night
5   describe the last time you were relax

我知道要使用CountVectorizer,我需要将列变成列表(这就是我试图做的事情)。

要应用TFIDF,我无法应用列表(并且我尝试将其转换为字符串)。

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import pandas as pd


df = pd.read_excel('data.xlsx')
col = df['all_cols']
corpus = col.values.tolist()

cv = CountVectorizer()
X = cv.fit_transform(corpus)

document = [' '.join(str(item)) for item in corpus]

tfidf_transformer=TfidfTransformer(smooth_idf=True,use_idf=True)
tfidf_transformer.fit(X)

feature_names=cv.get_feature_names()

tf_idf_vector=tfidf_transformer.transform(cv.transform([document]))

但是我仍然有这个错误

AttributeError                            Traceback (most recent call last)
<ipython-input-239-92f296939ea7> in <module>()
     16  
---> 17 tf_idf_vector=tfidf_transformer.transform(cv.transform([documento]))

AttributeError: 'list' object has no attribute 'lower'

2 个答案:

答案 0 :(得分:1)

我只是在猜测,因为我没有使用sklearn并且您没有发布完整的堆栈跟踪信息,但是异常看起来像它期望将字符串列表作为参数并调用字符串元素的“ lower()”

但是您正在做的是给它一个包含字符串的列表的列表:

corpus = [1,2,3]
document = [' '.join(str(item)) for item in corpus]

print (document)
>>> ['1','2','3']
print ([document])
>>> [['1','2','3']]

我敢打赌,如果您直接拨打电话,它将得到解决:

tf_idf_vector=tfidf_transformer.transform(cv.transform(document))

答案 1 :(得分:1)

您可以使用sklearn管道来简化此过程。

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import Pipeline 

tf_idf = Pipeline([('cv',CountVectorizer()), ('tfidf_transformer',TfidfTransformer(smooth_idf=True,use_idf=True))])


tf_idf_vector  = tf_idf.fit_transform(corpus)