2012-10-03 57 views
1

我想刪除停用詞。這裏是我的代碼以下python代碼中的錯誤

import nltk 
from nltk.corpus import stopwords 
import string 

u="The apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family (Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans." 

v="An orange is a fruit of the orangle tree. it is the most cultivated tree fruits" 

u=u.lower() 
v=v.lower() 

u_list=nltk.word_tokenize(u) 
v_list=nltk.word_tokenize(v) 

for word in u_list: 
    if word in stopwords.words('english'): 
     u_list.remove(word) 
for word in v_list: 
    if word in stopwords.words('english'): 
     v_list.remove(word) 

print u_list 
print "\n\n\n\n" 
print v_list 

但只有一些停止詞被刪除。請幫我這個

+0

當您定義'u' – avasal

+0

仍然無法使用時,會出現一個引號'''''''''''''沒有被移除 –

回答

1

與你在做什麼的問題是list.remove(X)僅刪除第一發生x,不是每x。要刪除每個實例,您可以使用filter,但我會選擇這樣的事情:

u_list = [word for word in u_list if word not in stopwords.words('english')] 
0

我會通過轉換的劈裂詞列表,並停止字的set列表中刪除文字和計算difference:在停止字

u_list = list(set(u_list).difference(set(stopwords.words('english')))) 

這應該正確取出出現次數。

+0

儘管這可能是正確的方法並且是可以接受的答案對於OP,應該注意的是,非停用詞的順序和計數不會被保留。 – sberry

0

我掙扎了一段時間了類似一塊使用remove(x)函數的代碼。我注意到只有約50%的停用詞被刪除。我知道這不是來自案件(我降低了我的話),也不是來自單詞(strip())周圍的增加的puntuation或其他字符。我的理論(我是一名初學者)是,當你刪除一個令牌時,列表會縮小,索引和列表項會滑動,但循環會從同一個索引繼續。因此它不會在每個單詞上循環。解決方法是用一個不是停用詞並且要保留的詞來增加一個新列表。