scala-word count

wordcount法1

import scala.io.Source
object wordcount {
  def main(args: Array[String]): Unit = {
    var m=Map.empty[String,Int]
    val file=Source.fromFile("C:/Users/HJ/Desktop/firstone.txt")
    for(x<- file.getLines()){
        val l=x.split(",").toList
      for(ele <-l ){
        m+=(ele->((m.getOrElse(ele,0))+1))

      }
    }
    println(m)
    m.foreach(println)

  }
}

# wordcount法2

import scala.io.Source

object HighlevelWordcount {
  def main(args: Array[String]): Unit = {
    val file=Source.fromFile("C:/Users/HJ/Desktop/firstone.txt")
    val wordcount=file.getLines().toList
    //结果:List(hello  world  hello  hello, welcome hello  welcome, world school)
      .flatMap(_.split("\t"))
    //结果:List(hello, world, hello, hello, welcome, hello, welcome, world, school)
      .map(x=>(x,1))
    //结果:List((hello,1), (world,1), (hello,1), (hello,1), (welcome,1), (hello,1), (welcome,1), (world,1), (school,1))
    //此步骤里面得到的是一个列表,里面的元素是元祖
    //元祖的用法:(2,3,5)._2    值为2
    //.groupBy((_._2))//:Map(1 -> List((hello,1), (world,1), (hello,1), (hello,1), (welcome,1), (hello,1), (welcome,1), (world,1), (school,1)))
      .groupBy((_._1))//Map(welcome -> List((welcome,1), (welcome,1)), school -> List((school,1)), world -> List((world,1), (world,1)), hello -> List((hello,1), (hello,1), (hello,1), (hello,1)))
        .mapValues(_.size)//Map(welcome -> 2, school -> 1, world -> 2, hello -> 4)
    println(wordcount)
  }

}

猜你喜欢

转载自blog.csdn.net/qq_42694416/article/details/85037480
今日推荐