RDD 练习:词频统计
一、词频统计:
1. 读文本文件生成 RDD lines
>>> lines = sc.textFile("file:///usr/local/spark/mycode/rdd/word.txt")
>>> lines.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214618187-334316636.jpg)
2. 将一行一行的文本分割成单词 words flatMap()
>>> words = lines.flatMap(lambda line:line.split())
>>> words.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214630995-1987177478.jpg)
3. 全部转换为小写 lower()
>>> wordslower = words.map(lambda word:word.lower())
>>> wordslower.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214642441-417843379.jpg)
4. 去掉长度小于3的单词 filter()
>>> words1 = wordslower.filter(lambda words:len(words)>2)
>>> words1.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214651596-1242233962.jpg)
5. 去掉停用词
>>> with open("/usr/local/spark/mycode/rdd/stopwords.txt") as f:
... stops = f.read().split()
>>> words1 = words1.filter(lambda word:word not in stops)
>>> words1.collect()
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214659024-483711107.jpg)
6. 转换成键值对 map()
>>> words1 = words1.map(lambda word:(word,1))
>>> words1.collect()
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214707052-1826052663.jpg)
7. 统计词频 reduceByKey()
>>> words1.reduceByKey(lambda a,b:b+b).collect()
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214720649-1883232803.jpg)
二、学生课程分数 groupByKey()
按课程汇总全总学生和分数
- 分解出字段
map()
- 生成键值对
map()
- 按键分组
- 输出汇总结果
>>> lines1 = sc.textFile("file:///usr/local/spark/mycode/rdd/chapter4-data01.txt")
>>> group1 = lines1.map(lambda line:line.split(',')).map(lambda line:(line[1],1)).groupByKey()
>>> group1.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214731812-2046163435.jpg)
三、学生课程分数 reduceByKey()
每门课程的选修人数
>>> lines1 = sc.textFile("file:///usr/local/spark/mycode/rdd/chapter4-data01.txt")
>>> groupNum = lines1.map(lambda line:line.split(',')).map(lambda line:(line[1],1)).reduceByKey(lambda a,b:a+b)
>>> groupNum.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214744511-638025265.jpg)
每个学生的选修课程数
>>> groupNum1 = lines1.map(lambda line:line.split(',')).map(lambda line:(line[0],1)).reduceByKey(lambda a,b:a+b)
>>> groupNum1.foreach(print)
![](https://img2020.cnblogs.com/blog/2152128/202104/2152128-20210405214752374-2034603727.jpg)