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

代码:#lines.flatMap(lambda line:line.lower().split()).collect()

   words=lines.flatMap(lambda line:line.lower().split()).collect()

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

代码:words.filter(lambda word : len(word)>3).collect()

5.去掉停用词

准备停用词文本

代码:

1.准备停用词文本:

lines = sc.textFile('file:///home/hadoop/stopwords.txt')
stop = lines.flatMap(lambda line : line.split()).collect()

 

 2.去除停用词:

words=lines.flatMap(lambda line:line.lower().split()).filter(lambda word : word not in stopword.txt)
words.collect()

6.转换成键值对 map()

代码:

words=words.map(lambda word : (word,1))

 

 

7.统计词频 reduceByKey()

代码:

words=words.map(lambda word : (word,1)).reduceBykey(lambda a,b:a+b).foreach(print)

二、学生课程分数 groupByKey()

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

先行代码:

lines = sc.textFile('file:///home/hadoop/chapter4-data01.txt')

lines.take(5)

1. 分解出字段 map()

代码:

lines.map(lambda line:line.split(',')).take(5)

2. 生成键值对 map()

代码:

lines.map(lambda line:line.split(',')).map(lambda line:(line[1],(line[0],line[2]))).take(5)

3. 按键分组 

代码:

lines.map(lambda line:line.split(',')).map(lambda line:(line[1],(line[0],line[2]))).groupByKey().take(5)

4. 输出汇总结果

代码: 

groupByCoure = lines.map(lambda line:line.split(',')).map(lambda line:(line[1],(line[0],line[2]))).groupByKey()

for i in groupByCoure.first()[1]:
... print(i)
...

 

 

 

三、学生课程分数 reduceByKey()

-- 每门课程的选修人数

代码:

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

-- 每个学生的选修课程数

代码: 

lines.map(lambda line:line.split(',')).map(lambda line:(line[1],1) ).reduceByKey(lambda a,b:a+b).take(5)

posted @ 2021-04-03 18:36  starrysky~ocean  阅读(137)  评论(0编辑  收藏  举报