RDD编程
1.读文本文件生成RDD lines
lines=sc.textFile('file:///home/hadoop/word.txt')
2.将一行一行的文本分割成单词 words
words=lines.flatMap(lambda line:line.split())
3.全部转换为小写
words=lines.flatMap(lambda line:line.lower().split())
4.去掉长度小于3的单词
words1=lines.flatMap(lambda line:line.split()).filter(lambda line:len(line)>3)
5.去掉停用词
lines=sc.textFile('file:///usr/loaca/spark/stopwords.txt')
stop = lines.flatMap(lambda line : line.split()).collect()
lines=sc.textFile("f
words=lines.flatMap(lambda line:line.lower().split()).filter(lambda word:word not in stop)
le:///home/hadoop/word.txt")
6.转换成键值对 map()
words1=words.map(lambda word:(word.lower(),1))
7.统计词频 reduceByKey()
wordskv.reduceByKey(lambda a,b:a+b).collect()
8、按字母顺序排序 sortBy(f)
words2=words.map(lambda word:(word.lower(),1)).reduceByKey(lambda a,b:a+b).sortBy(lambda word:word[0])
9、按词频排序 sortByKey()
wordsk3=words.map(lambda word:(word.lower(),1)).reduceByKey(lambda a,b:a+b)
words3.sortByKey().collect()
二、学生课程分数案例
- 总共有多少学生?map(), distinct(), count()
-
lines=sc.textFile('file:///usr/local/spark/chapter4-data01.txt')
-
lines.map(lambda line : line.split(',')[0]).distinct().count()
-
- 开设了多少门课程?
-
lines.map(lambda line : line.split(',')[1]).distinct().count()
-
- 每个学生选修了多少门课?map(), countByKey()
-
lines.map(lambda line : line.split(',')).map(lambda line:(line[0],(line[1],line[2]))).countByKey()
-
- 每门课程有多少个学生选?map(), countByValue()
-
lines.map(lambda line : line.split(',')).map(lambda line : (line[1])).countByValue()
-
- Tom选修了几门课?每门课多少分?filter(), map() RDD
-
lines.filter(lambda line:'Tom' in line).map(lambda line:line.split(',')).collect()
-
- Tom选修了几门课?每门课多少分?map(),lookup() list
-
lines.map(lambda line:line.split(',')).map(lambda line:(line[0],(line[1],line[2]))).lookup("Tom")
-
- Tom的成绩按分数大小排序。filter(), map(), sortBy()
-
lines.filter(lambda line:"Tom" in line).map(lambda line:line.split(',')).sortBy(lambda line:(line[2])).collect()
-
- Tom的平均分。map(),lookup(),mean()
- from numpy import mean
- tomlist=lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[2])).lookup("Tom")
- mean([int(x) for x in tomlist])
-