AttributeError:'list'对象没有属性analyze

时间:2014-03-28 20:22:19

标签: python scikit-learn tf-idf

我试图计算tf-idf,这是我的代码:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA

train_set = ["The sky is blue.", "The sun is bright."] #Documents
test_set = ["The sun in the sky is bright sun."] #Query
stopWords = stopwords.words('english')

vectorizer = CountVectorizer(stopWords)
#print vectorizer
transformer = TfidfTransformer() 
#print transformer

trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray

transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()

transformer.fit(testVectorizerArray)
print
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()

我收到此错误:

Traceback (most recent call last):
File "tf-idf2.py", line 16, in <module>
trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
File "/usr/lib/pymodules/python2.7/sklearn/feature_extraction/text.py", line 341,
in fit_transform
term_count_current = Counter(self.analyzer.analyze(doc))
AttributeError: 'list' object has no attribute 'analyze'

我使用的是scikit版本0.14.1。

1 个答案:

答案 0 :(得分:0)

CountVectorizer(stopWords)

应该是

CountVectorizer(stop_words=stopWords)

除非在文档中另有说明,否则始终对scikit-learn对象的构造函数参数使用关键字参数。