05 RDD编程

一、词频统计:

1.读文本文件生成RDD lines

2.将一行一行的文本分割成单词 words flatmap()

lines=sc.textFile("file:///usr/local/spark/mycode/wordcount/word.txt")
words = lines.flatMap(lambda line:line.split()).collect()
print(words)

3.全部转换为小写 lower()

sc.parallelize(words).map(lambda line: line.lower()).collect()

4.去掉长度小于3的单词 filter()

words1=sc.parallelize(words)
words1.collect()
words1.filter(lambda word:len(word)>3).collect()

5.去掉停用词

with open('/usr/local/spark/mycode/stopwords.txt')as f:
    stops=f.read().split()
words1.filter(lambda word:word not in stops).collect()

6.转换成键值对 map()

words1.map(lambda word:(word,1)).collect()

7.统计词频 reduceByKey()

words1.map(lambda word:(word,1)).reduceByKey(lambda a,b:b+b).collect()

8.按字母顺序排序 sortBy(f)

words1.map(lambda word : (word,1)).reduceByKey(lambda a,b:a+b).sortBy(lambda word:word[0]).collect()

9.按词频排序 sortByKey()

 words1.map(lambda word:(word.lower(),1)).reduceByKey(lambda a,b:a+b).sortBy(lambda word:word[1],False).collect()

 

二、学生课程分数案例

1.总共有多少学生?map(), distinct(), count()

2.开设了多少门课程?

>>> lines.map(lambda line : line.split(',')[0]).distinct().count()
>>> lines.map(lambda line : line.split(',')[1]).distinct().count()

 

3.每个学生选修了多少门课?map(), countByKey()

lines.map(lambda line : line.split(',')).map(lambda line:(line[0],line[2])).countByKey()

 

4.每门课程有多少个学生选?map(), countByValue()

lines.map(lambda line : line.split(',')).map(lambda line : (line[1])).countByValue()

 

5.John选修了几门课?每门课多少分?filter(), map() RDD

lines.filter(lambda line:"John" in line).map(lambda line:line.split(',')).collect()

 

6.John选修了几门课?每门课多少分?map(),lookup()  list

lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[1])).lookup("John")

lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[2])).lookup("John")

 

7.John的成绩按分数大小排序。filter(), map(), sortBy()

lines.filter(lambda line:"John" in line).map(lambda line:line.split(',')).sortBy(lambda line:(line[2]),False).collect()

 

8.John的平均分。map(),lookup(),mean()

import numpy as np
meanlist=lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[2])).lookup("John")
np.mean([int(x) for x in meanlist])

 

posted @ 2021-04-17 19:48  金腰带小拳石  阅读(59)  评论(0编辑  收藏  举报