scala words

33 阅读1分钟
package words

import java.io.FileWriter

object words01 {
  def main(args: Array[String]): Unit = {
    //1.读入test.txt内容
    //  Source.fromFile().mkString
    //2.对字符串进行拆分 把句子变成一个个单词
    //  split

    //1
    val content = scala.io.Source.fromFile("./test.txt").mkString
    println(content)
    //2 对字符串进行拆分 使用空格

    val rst =  content.split("\W+").map(ele=>ele.toLowerCase)

    //3 空的容器保存键值对数据:键:单词 值:次数
    val map = scala.collection.mutable.Map[String,Int]()
    rst.foreach(word => {
      //如果word在map中存在 则把值+1
      if (map.contains(word)){
        map(word)+= 1
      }
      else {   //如果word在map中不存在 则值设为1
        //map += word ->1
        map(word)=1
      }
    })

    //4.排序

    //按照单词出现的频率 从高到低排序
    //map是无序的 不能做排序
    //List是可以排序的
    val wordLists = map.toList.sortBy(_._2).reverse

    //5.将结果写入文件中
    val writer = new FileWriter("result.txt")
    wordLists.foreach(ele =>{
      writer.write(s"${ele._1}:${ele._2} \n")
    })
    writer.close()

    //6
    map.foreach(println)
  }
}

目标:统计单词出现的次数 按降序排序 并把结果保存到文件中

  • 第一步:建立一个容器 空Map
  • 第二步:用Map的空contains方法判断 单词的map的键是否存在:1)存在:则将值+1 2)不存在:则将值设为1
  • 第三步:foreach方法输出结果