一、词频统计:
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()
1 words=lines.flatMap(lambda line:line.lower().split()).collect() 2 words=lines.flatMap(lambda line:line.lower().split()) 3 words.collect()
4.去掉长度小于3的单词 filter()
words.filter(lambda word : len(word)>3).collect()
5.去掉停用词
1 # 准备文本 2 lines = sc.textFile('file:///home/hadoop/stopwords.txt') 3 stop = lines.flatMap(lambda line : line.split()).collect() 4 # 去除停用词 5 words=lines.flatMap(lambda line:line.lower().split()).filter(lambda word : word not in stop) 6 words.collect()
6.转换成键值对 map()
words.map(lambda word : (word,1))
7.统计词频 reduceByKey()
words.map(lambda word : (word,1)).reduceByKey(lambda a,b:a+b).foreach(print)
8.按字母顺序排序 sortBy(f)
words.map(lambda word : (word,1)).reduceByKey(lambda a,b:a+b).sortBy(lambda word:word[0]).collect()
9.按词频排序 sortByKey()
words.map(lambda word : (word,1)).reduceByKey(lambda a,b:a+b).sortByKey().collect()
二、学生课程分数案例
- 共有多少学生?map(), distinct(), count()
- 开设了多少门课程?
- 每个学生选修了多少门课?map(), countByKey()
- 每门课程有多少个学生选?map(), countByValue()
- Tom选修了几门课?每门课多少分?filter(), map() RDD
- Tom选修了几门课?每门课多少分?map(),lookup() list
- Tom的成绩按分数大小排序。filter(), map(), sortBy()
- Tom的平均分。map(),lookup(),mean()