zoukankan      html  css  js  c++  java
  • 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 }  
  • 相关阅读:
    命令别名与历史命令
    Shell的变量功能
    Shell的变量功能
    认识BASH这个Shell
    vim程序编辑器
    其他vim使用注意事项
    vim的额外功能
    六、集合
    五、字典
    四、列表 元组
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7918784.html
Copyright © 2011-2022 走看看