4.RDD操作

5.RDD操作综合实例

一、词频统计

A. 分步骤实现

 

  1. 准备文件
    1. 下载小说或长篇新闻稿

 

  1. 上传到hdfs上

hdfs dfs -put /home/hadoop/5case.txt ./5case

  1. 读文件创建RDD

lines = sc.textFile("/user/hadoop/5case/5case.txt")

 

  1. 分词

pattern = ''' |,|\.|\’|“|”| '''   |为间隔符    \为防转义符

 words = lines.flatMap(lambda line:re.split(pattern,line))

 

  1. 排除大小写lower(),map()

words.map(lambda word:word.lower())


标点符号re.split(pattern,str),flatMap(),
停用词,可网盘下载stopwords.txt,filter(),

with open("/home/hadoop/stopwords.txt") as stoplines:
     stopwords = stoplines.read().split()

words.filter(lambda words:word not in stopwords)

word.filter(lambda x:x not in stopwords)过滤停顿词


长度小于2的词filter()

word.filter(lambda x:x not in stopwords) 

 

words2.filter(lambda x:len(x)>2) 过滤长度小于2的单词

  1. 统计词频

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

  1. 按词频排序

words.reduceByKey(lambda a,b:a+b)

word4.sortBy(lambda x:x[1],False,1)  ('students', 5)     x[ 1 ]è5  False为降序,True为升序  1为处理存放的块数,默认为10块

  1. 输出到文件

word5.saveAsTextFile("output")

  1. 查看结果

dfs dfs -cat /user/Hadoop/文件所在路径

posted @ 2022-03-29 20:08  鲍bee  阅读(24)  评论(1)    收藏  举报