package hfd.test32import java.io.PrintWriter import scala.io.Sourceobject Test {def main(args: Array[String]): Unit = {//从文件1.txt中,读入内容val content = Source.fromFile("1.txt").mkStringprintln(content)//把字符串中的每个单词,拆出来// \\W+:答谢字符串表示:非字(不是一个字的字符,列如:空格,逗号,句号,换行。。。)//+:一个或者多个val arr = content.split("\\W+")arr.foreach(println)//如果有一个字符串数组:// val arr1= Array("thank","you","very","much","very")val m1 = scala.collection.mutable.Map[String, Int]()arr.foreach(word => {//检查是否出现?if (m1.contains(word)) {//把票数+1m1(word) += 1} else {//票数为1m1(word) = 1}})//对于m1,他是一共Map(thank:10,is:5),现在需要对它进行排序,把出现次数最多的放在最前面,然后再输出//(thank,10)//只要排序之前的结果的前15个?在List中取出前15个?val sortedM1 = m1.toList.sortWith((a, b) => a._2 > b._2).filter(a => a._1.length > 2).slice(0, 15)//输出排序后的Map// sortedM1.foreach { case (word, cishu) => println(s"${word}:${cishu}") }//把结果保存到一个新的文件中val writer = new PrintWriter("3.txt")writer.println("统计的结果为:")sortedM1.foreach{case (word,cishu)=>writer.println(s"${word}:${cishu}")}writer.close()//结束写入//thank:2// you:1//very:2//much:1} }