05 RDD编程
2021/4/18 14:55:18
本文主要是介绍05 RDD编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、词频统计:
1.读文本文件生成RDD lines
lines = sc.textFile('file:///home/hadoop/word.txt')
2.将一行一行的文本分割成单词 words flatmap()
words=lines.flatMap(lambda line:line.split()) words.collect()
3.全部转换为小写 lower()
words=lines.flatMap(lambda line:line.lower().split()) words.collect()
4.去掉长度小于3的单词 filter()
words=words.filter(lambda word:len(word)>3) words.collect()
5.去掉停用词
![复制代码](/images/baidian.png)
with open('/home/hadoop/stopwords.txt') as f: stops=f.read().split() words=words.filter(lambda word:word not in stops) words.count() words.collect()
![复制代码](/images/baidian.png)
6.转换成键值对 map()
words=words.map(lambda word:(word,1))
7.统计词频 reduceByKey()
words=words.reduceByKey(lambda a,b:a+b)
8.按字母顺序排序 sortBy(f)
words=words.sortBy(lambda word:word[0]) words.collect()
9.按词频排序 sortByKey()
words=words.sortByKey() words.collect()
二、学生课程分数案例
lines = sc.textFile('file:///home/hadoop/chapter4-data01.txt') lines.take(5)
1.总共有多少学生?map(), distinct(), count()
lines.map(lambda line : line.split(',')[0]).distinct().count()
2.开设了多少门课程?
lines.map(lambda line : line.split(',')[1]).distinct().count()
3.每个学生选修了多少门课?map(), countByKey()
lines.map(lambda line : line.split(',')).map(lambda line:(line[0],(line[1],line[2]))).countByKey()
4.每门课程有多少个学生选?map(), countByValue()
lines.map(lambda line : line.split(',')).map(lambda line : (line[1])).countByValue()
5.Les选修了几门课?每门课多少分?filter(), map() RDD
lines.filter(lambda line:"Les" in line).map(lambda line:line.split(',')).collect()
6.Les选修了几门课?每门课多少分?map(),lookup() list
lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[1])).lookup("Les") lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[2])).lookup("Les")
7.Les的成绩按分数大小排序。filter(), map(), sortBy()
lines.filter(lambda line:"Les" in line).map(lambda line:line.split(',')).sortBy(lambda line:(line[2])).collect()
8.Les的平均分。map(),lookup(),mean()
import numpy as np meanlist=lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[2])).lookup("Les") np.mean([int(x) for x in meanlist])
这篇关于05 RDD编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)