2015-11-05 43 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()])