2015-11-05 44 views
0

這是一個用pyspark ipython筆記本編寫的python程序。我正在嘗試使用for循環來計算每個RDD(可以視爲文件)列表中「名稱」中給出的單詞實例的數量。我想要將每個文件中單詞的計數存儲在一個名稱與單詞相同的列表中。將loop中的內容存儲在列表中python

例如,假設第一RDD中的詞哈利數爲1214,第二RDD中的詞數爲1506 n等等。我想創建一個列表 harryList = [1214,1506,1825,2933,3748,2617,2887]

這個名字列表是動態的。

names = ['harry', 'hermione','ron','hagrid'] 
rdds = [hp1RDD,hp2RDD,hp3RDD,hp4RDD,hp5RDD,hp6RDD,hp7RDD] 

for n in names: 
    a = [] 


    for x in rdds: 
     a.append(x.flatMap(lambda line: line.split(" ")).filter(lambda word: word==n).count()) 

    print a  

與上面的代碼我可以打印列表中的內容,但我不能保存它上面顯示的方式。

+0

使用的字典,而不是其中的關鍵是'harry'和值是值 –

+1

的,你只需要準確的單詞列表?我的意思是,你需要** hagrid **還是** hagrid **作爲** hagrid **? –

+2

將RDD轉換爲單詞列表並使用'collections.Counter'。 –

回答

0

如果你不介意:

  • 的話就像海格海格

使用collections.Counter將幫助獨立計算:

from collections import Counter 

hp1RDD = "harry potter has a girlfriend who's name is hermione granger and a friend called ron. harry has an uncle who's name is hagrid. hagrid is a big guy" 
hp2RDD = "harry potter is the best movie I've ever saw. hermione is very beautfiful" 

names = ['harry', 'hermione','ron','hagrid'] 
rdds = [hp1RDD, hp2RDD] 
results = dict() 

for name in names: 
    tmp_list = list() 

    for rdd in rdds: 
     count = Counter(rdd.split()) 
     tmp_list.append(count[name]) 
    results[name] = tmp_list 

print results 

此外,你可以只用lower()使用不區分大小寫的版本:

count = Counter([x.lower() for x in rdd.split()])