scala统计一个文件夹下面所有文件的单词出现的总次数

来源:互联网 发布:海尔软件待遇怎么样 编辑:程序博客网 时间:2024/06/05 02:34



import java.io.File
import scala.io.Source

class WorldCount {
  var map = Map.empty[String, Int]
  def scanDir(file: File) {
    file.listFiles().foreach { f => if (f.isFile()) readFile(f) }
  }
  def readFile(file: File) {
    val f = Source.fromFile(file,"utf-8")
    for (line <- f.getLines()) {
      for (word <- line.split("\t|,|\\\\|\\+|\\-|\\(|\\)|\\[|\\]|!|:|\\.|>|<|\\{|\\}|\\?|\\*| |\\/|\"")) {
        if (map.contains(word))
          map += (word -> (map(word) + 1))
        else
          map += (word -> 1)
      }
    }
  }
}
object WorldCount {

  def main(args: Array[String]): Unit = {
    val wordCount = new WorldCount()
    wordCount.scanDir(new File("D:\\scalaDir"))
    wordCount.map.foreach{x=>println("world:"+x._1+"  count:"+x._2)}
  }
}


0 0
原创粉丝点击