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)
}
}
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)
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容