使用Scala實現文件單詞計數

 
package com.dtapp.base

import scala.io.Source

object WCntApp {
  def main(args: Array[String]) {
    val file = Source.fromFile("E:\\abc.txt", "UTF-8")
    var map = Map.empty[String, Int]
    for (line <- file.getLines){
      val words = line.split(" ").toList
      for(wd <- words) {
        if (map.contains(wd))
          map += (wd -> (map(wd) + 1))
        else
          map += (wd -> 1)
      }
    }
    println("map:" + map)
    file.close()
  }
}
相關文章
相關標籤/搜索