2017-02-13 155 views
0

我想計算幾個csv文件中單詞的出現次數。首先,我想展示10個最常遇到的單詞,其中有停用詞,然後沒有停用詞。在沒有停用詞的多個csv文件中計算單詞的頻率

這是我的代碼:

import nltk 
nltk.download("stopwords") 


from nltk.corpus import stopwords 


myfile = sc.textFile('./Sacramento*.csv') 


counts = myfile.flatMap(lambda line: line.split(",")).map(lambda word: (word, 1)).reduceByKey(lambda v1,v2: v1 + v2) 


sorted_counts = counts.map(lambda (a, b): (b, a)).sortByKey(0, 1).map(lambda (a, b): (b, a)) 


first_ten = sorted_counts.take(10) 


first_ten 
Out[7]: 
[(u'Residential', 917), 
(u'2', 677), 
(u'CA', 597), 
(u'3', 545), 
(u'SACRAMENTO', 439), 
(u'ours', 388), 
(u'0', 387), 
(u'4', 277), 
(u'Mon May 19 00:00:00 EDT 2008', 268), 
(u'Fri May 16 00:00:00 EDT 2008', 264)] 


cachedStopWords = stopwords.words("english") 


result_ll = counts.map(lambda (a, b): (b, a)).sortByKey(0, 
1).map(lambda (a, b): (b, a)) 


print [i for i in result_ll.take(10) if i not in cachedStopWords] 

但產量仍與停止的話 - 「我們」 也停用詞

[(u'Residential」,917),(U'2之間(u'CA',597),(u'3',545),(u'SACRAMENTO',439),(u'ours',388),(u'0',387), (u'4',277),(u'Mon May 19 00:00:00 EDT 2008',268),(u'Fri May 16 00:00:00 EDT 2008',264)]

How我應該改變我的代碼,所以輸出沒有停止詞:「我們的」?

回答

0

你必須在最後一行的錯誤,它應該像

print [i for i in result_ll.take(10) if i[0] not in cachedStopWords] 

因爲i[0]保存實際字。