hadoop+spark词频统计+时间记录

本文介绍了如何在Scala中使用ApacheSpark进行单词计数,从文本文件中读取数据,处理、统计词频,并将结果保存到输出文件的过程。
摘要由CSDN通过智能技术生成

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import java.io.PrintWriter


object WordCount {
    def main(args: Array[String]) {
        val inputFile =  "file:///usr/local/spark/mycode/wordcount/A.txt"
        val conf = new SparkConf().setAppName("WordCount").setMaster("local[2]")
        val sc = new SparkContext(conf)
                val textFile = sc.textFile(inputFile)
                val startTime = System.currentTimeMillis()
                val wordCount = textFile.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
                val endTime = System.currentTimeMillis()
                val totalTime = endTime - startTime
                val outputFilePath = "file:///usr/local/spark/mycode/wordcount/output_A.txt"
                val writer = new PrintWriter(outputFilePath)
                wordCount.sortBy(-_._2).collect().foreach { case (word, count) => writer.println(s"$word: $count") }
                writer.close()
                println(s"WordCount completed in ${totalTime}ms")
    
    }
}

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值