05 RDD编程

2021/4/17 22:55:44

本文主要是介绍05 RDD编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

1.读文本文件生成RDD lines

lines = sc.textFile('file:///home/hadoop/word.txt')

lines.collect()

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

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

words.collect()

3.全部转换为小写

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

words.collect()

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

words=lines.flatMap(lambda line:line.split()).filter(lambda line:len(line)>3)

words.collect()

5.去掉停用词

  1.准备停用词文本:

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

stop

  2.去除停用词:

 lines=sc.textFile("file:///home/hadoop/word.txt")

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

words
words.collect()

6.转换成键值对 map()

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

wordskv.collect()

7.统计词频 reduceByKey()

wordskv.reduceByKey(lambda a,b:a+b).collect()

8、按字母顺序排序 sortBy(f)

wordskv=words.map(lambda word:(word.lower(),1)).reduceByKey(lambda a,b:a+b).sortBy(lambda word:word[0])

wordskv.collect()

9、按词频排序 sortByKey()

wordskv=words.map(lambda word:(word.lower(),1)).reduceByKey(lambda a,b:a+b)

wordskv.sortByKey().collect()

二、学生课程分数案例

  • 总共有多少学生?map(), distinct(), count()
  • 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()
  • Allen选修了几门课?每门课多少分?filter(), map() RDD
  • lines.filter(lambda line:"Allen" in line).map(lambda line:line.split(',')).collect()
  • Allen选修了几门课?每门课多少分?map(),lookup()  list
  • lines.map(lambda line:line.split(',')).map(lambda line:(line[0],(line[1],line[2]))).lookup("Allen")
  • Allen的成绩按分数大小排序。filter(), map(), sortBy()

     

  • lines.filter(lambda line:"Allen" in line).map(lambda line:line.split(',')).sortBy(lambda line:(line[2])).collect()
  • Allen的平均分。map(),lookup(),mean()
  • import numpy as np

  • meanlist=lines.map(lambda line:line.split(',')).map(lambda line:(line[0],line[2])).lookup("Allen")
  • np.mean([int(x) for x in meanlist])



这篇关于05 RDD编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程