一:方法
package test5
import java.io.PrintWriter
import scala.io.Source
//可变的Map
import scala.collection.mutable
object test5_1 {def main(args: Array[String]): Unit = {
//1.读入文件val content = Source.fromFile("1.txt").mkString
// println(content)//2.拆分字符串-->单词数组
// val rs = content.split(",")正则表达式
// W:表示非字符(,空格,?...)
// W+:多个非字符val rs = content.split("\\w+")
// println("-"*40)
// rs.foreach(println)//3.统计出现的频率val wordsMap = mutable.Map[String,Int]()rs.foreach(w => {val word = w.toLowerCase()//全小写//是否出现if(wordsMap.contains(word)){wordsMap(word)+=1}else{wordsMap(word) = 1}})//4.根据出现的次数从高到低排序//Map不能直接排序,需要转成有序的集合val orderList = wordsMap.toList.sortWith((a,b)=>a._2>b._2)//输出Map//5.保存结果,涉及到写入文件val writer = new PrintWriter("output.txt")for (e<- orderList){println(e._1,e._2)writer.println(s"${e._1}:${e._2}次")}writer.close()//关闭}
}