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

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

代码如下 

import java.io.{FileNotFoundException, File}


import scala.io.Source

object WordCount extends App {

  val path = "C:\\Users\\Administrator\\Desktop\\ff\\fzsExample\\src"
  val file = new File(path)
  val files = file.listFiles().filter(_.isFile)
  val mapData = scala.collection.mutable.Map[String, Int]()

  def readFile(item : File): Unit = {
    try {
        Source.fromFile(item).getLines().flatMap(_.split("\\s+")).toList.map(x => {
        mapData.get(x) match {
          case Some(b) => mapData += ( x -> b.+(1))
          case None => mapData += ( x -> 1)
        }
      })
    }catch{
      case e1: FileNotFoundException => println("FileNotFoundException")
      case e2: RuntimeException => println("RuntimeException")
      case e3: Exception => println("Exception")
    }
  }

  files.map(readFile)
  println(mapData)
}


版权声明:本文为u012016268原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。