02 使用spark进行词频统计【scala交互】

我们已经在CentOS7中安装了spark,本节将展示如何在spark中通过scala方式交互的进行词频统计。

1 系统、软件以及前提约束

2 操作

  • 1.使用xshell以root登录到192.168.100.200
  • 2.新建一个文件,输入一些字符串,上传到HDFS
# 进入hadoop的bin目录
cd /root/hadoop-2.5.2/bin
# 编辑word,加入以下内容,保存退出
I am zhangli
I am xiaoli
who are you
I am ali
hello jiangsu wanhe
wanhe
# 上传word到HDFS
./hdfs dfs -put word /word
# 查看
./hdfs dfs -cat /word
  • 3.进入到spark命令行
# 进入spark的命令目录
cd /root/spark-2.2.1-bin-hadoop2.7/bin
# 进入spark命令行
./spark-shell
  • 4.在spark命令行交互执行以下命令
#创建一个上下文环境,以HDFS的/word作为输入
scala > val textFile = sc.textFile("/word")
#统计/word共有多少行
scala > textFile.count()
#打印/word内容
scala > textFile.collect().foreach(println)
#过滤哪些行包含"I"
scala > val linesWithSpark = textFile.filter(line => line.contains("I"))
#包含"I"总共有多少行
scala > linesWithSpark.count()
#统计单词频率
scala > val wordCounts = textFile.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
#打印统计结果
scala > wordCounts.collect()

以上,就是在spark当中通过scala的交互方式进行词频统计。

转载于:https://www.jianshu.com/p/92257e814e59

猜你喜欢

转载自blog.csdn.net/weixin_33696106/article/details/91051978