2012-04-20 22 views
1

NLTK比較,我有一個Python字典,看起來像:如何將我的輸入默認的字典爲小寫在Python中

freq_distribution = nltk.FreqDist(filtered_words)    
top_words = freq_distribution.keys()[:4]  
print top_words     

此:

defaultdict(<type 'int'>, {u'RT': 1, u'be': 1, u'uniforms': 1, u'@ProFootballWkly:': 1, u'in': 1, u'Nike': 1, u'Brooklyn.': 1, u'ET': 1, u"NFL's": 1, u'will': 1, u'a.m.': 1, u'at': 1, u'unveiled': 1, u'Jimmy': 3, u'11': 1, u'new': 1, u'The': 2, u'today': 1}) 

我與它的處理輸出包含單詞「The」的前4個單詞,我試圖在此過程發生之前包含Dolch「常用」單詞的刪除:

filtered_words = [w for w in word_count \ 
       if not w in stopwords.words('english')] 

問題是,我仍然以「The」結尾,因爲來自NLTK的所有(停用詞)都是小寫字母。我需要一種方法來接受word_count的輸入並將其切換爲小寫。我曾嘗試將在各個領域,如低():

freq_distribution = nltk.FreqDist(word_count.lower()) 

但都沒有成功,因爲我反覆出現以下錯誤:

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

回答

4
filtered_words = [w for w in word_count \ 
      if w.lower() not in stopwords.words('english')] 

這小寫w檢查它是否在停用詞列表中。因此,如果w是「The」,則在檢查之前它將被轉換爲the。由於「the」在列表中,它將被過濾掉。

+0

這絕對是一個很好的答案,應該解決op的問題。在我看來,'w.lower()不是in'而不是'w.lower()in'會更具可讀性,但是這顯然非常小,我想我會提到它。 – 2012-04-20 02:28:46

+0

@Nolen,是的,我只是從原來的複製和粘貼。但編輯是一個好主意。 – dhg 2012-04-20 02:31:10

+0

非常感謝你,我以爲我走在了正確的軌道上。 – secumind 2012-04-20 13:55:44