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



1
import scala.io.Source 2 3 object WordCount extends App { 4 5 val path = "C:\Users\Administrator\Desktop\ff\fzsExample\src" 6 val file = new File(path) 7 val files = file.listFiles().filter(_.isFile) 8 val mapData = scala.collection.mutable.Map[String, Int]() 9 10 def readFile(item : File): Unit = { 11 try { 12 Source.fromFile(item).getLines().flatMap(_.split("\s+")).toList.map(x => { 13 mapData.get(x) match { 14 case Some(b) => mapData += ( x -> b.+(1)) 15 case None => mapData += ( x -> 1) 16 } 17 }) 18 }catch{ 19 case e1: FileNotFoundException => println("FileNotFoundException") 20 case e2: RuntimeException => println("RuntimeException") 21 case e3: Exception => println("Exception") 22 } 23 } 24 25 files.map(readFile) 26 println(mapData)

方法二:

1  val wordlist = Source.fromFile(item).getLines().flatMap(line => line.split(" ")).map(word => (word, 1))  
2    //方法一:先groupBy再map  
3    wordlist.groupBy(_._1).map {  
4      case (word, list) => (word, list.size)  
5    }.foreach(println)  
6 
7 }  
原文地址:https://www.cnblogs.com/wzj4858/p/7918784.html