【发布时间】:2021-05-10 22:25:20
【问题描述】:
我正在编写一个函数来执行自定义单词删除、词干提取(获取单词的根形式),然后是 tf-idf。
我的函数输入数据是一个列表。如果我尝试在单个列表上进行自定义单词删除,那是可行的,但是当我将它组合到函数中时,我得到一个属性错误:
AttributeError: 'list' 对象没有属性 'lower'
这是我的代码:
def tfidf_kw(K):
# Select docs in cluster K
docs = np.array(mydata2)[km_r3.labels_==K]
ps= PorterStemmer()
stem_docs = []
for doc in docs:
keep_tokens = []
for token in doc.split(' '):
#custom stopword removal
my_list = ['model', 'models', 'modeling', 'modelling', 'python',
'train','training', 'trains', 'trained','test','testing', 'tests','tested']
token = [sub_token for sub_token in list(doc) if sub_token not in my_list]
stem_token=ps.stem(token)
keep_tokens.append(stem_token)
keep_tokens =' '.join(keep_tokens)
stem_docs.append(keep_tokens)
return(keep_tokens)
更多代码适用于 tf-idf,它有效。这是我需要帮助的地方,以了解我做错了什么?
token = [sub_token for sub_token in list(doc) if sub_token not in my_list]
这是完整的错误:
AttributeError Traceback (most recent call last)
<ipython-input-154-528a540678b0> in <module>
49 #return(sorted_df)
50
---> 51 tfidf_kw(0)
<ipython-input-154-528a540678b0> in tfidf_kw(K)
20
21
---> 22 stem_token=ps.stem(token)
23 keep_tokens.append(stem_token)
24
~/opt/anaconda3/lib/python3.8/site-packages/nltk/stem/porter.py in stem(self, word)
650
651 def stem(self, word):
--> 652 stem = word.lower()
653
654 if self.mode == self.NLTK_EXTENSIONS and word in self.pool:
AttributeError: 'list' object has no attribute 'lower'
在第 51 行,上面写着 tfidf_kw(0),这就是我检查函数 k=0 的地方。
【问题讨论】:
标签: python list function stop-words