RDD练习:词频统计

RDD 练习:词频统计

一、词频统计:

1. 读文本文件生成 RDD lines

>>> lines = sc.textFile("file:///usr/local/spark/mycode/rdd/word.txt")
>>> lines.foreach(print)

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

>>> words = lines.flatMap(lambda line:line.split())
>>> words.foreach(print)

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

>>> wordslower = words.map(lambda word:word.lower())
>>> wordslower.foreach(print)

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

>>> words1 = wordslower.filter(lambda words:len(words)>2)
>>> words1.foreach(print)

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()

6. 转换成键值对 map()

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

7. 统计词频 reduceByKey()

>>> words1.reduceByKey(lambda a,b:b+b).collect()

二、学生课程分数 groupByKey()

按课程汇总全总学生和分数

  1. 分解出字段 map()
  2. 生成键值对 map()
  3. 按键分组
  4. 输出汇总结果
>>> 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)

三、学生课程分数 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)

每个学生的选修课程数

>>> groupNum1 = lines1.map(lambda line:line.split(',')).map(lambda line:(line[0],1)).reduceByKey(lambda a,b:a+b)
>>> groupNum1.foreach(print)

posted @ 2021-04-05 21:51  1After909  阅读(173)  评论(0编辑  收藏  举报