scala统计词频

Scala 复制代码
package test23

import java.io.PrintWriter
import scala.io.Source
object test {
  def main(args: Array[String]): Unit = {
    //从文件1.txt中,读取内容
    val content = Source.fromFile("1.txt").mkString
    println(content)
    //把字符串中的每个单词,拆出来

    //正则表达式
    //\\w+:大写字符表示:非字(不是一个字的字符。例如:空格,逗号,句号,换行。。。。)
    // +:一个或者多个
    val arr = content.split("\\w ")//得到一个字符串数组

    arr.foreach(println)
    //如果有一个字符串数组:
    val arr1= Array("thank","you","much","thank","very")

    val m1 = scala.collection.mutable.Map[String,Int]()
    arr1.foreach(word =>{
      //检查是否出现过
      if(m1.contains(word)){
        //把票数+1
        m1(word)+=1
      }else{
        //票数为1
        m1(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, count) =>
//      println(s"${word}:${count}")
    //4.把结果保存到一个新文件中
    //开始写入
    val writer = new PrintWriter("3.txt")
    //排序后输出Map
    //把结果保存到一个新文件中
    writer.println("统计结果是:")
    sortedM1.foreach{case(word,cishu)=>println(s"${word}:${cishu}")}
    writer.close()//结束写入
  }

}
相关推荐
fliter几秒前
WAF 机器学习推理从 1519μs 压到 275μs,Cloudflare 是怎么做到的
后端
Moment7 分钟前
2026年,为什么NestJS + Monorepo越来越流行了 ❓❓❓
前端·后端·面试
IT果果日记8 分钟前
人大金仓使用Flink-CDC
大数据·数据库·后端
yugi9878388 分钟前
MATLAB 实现平板裂纹扩展模拟、气孔/夹杂物分析
开发语言·matlab
Gopher_HBo10 分钟前
阻塞队列之SynchronousQueue
后端
understandme12 分钟前
30 毫秒教会你怎么在 TKE 搭建 Istio
后端
神奇小汤圆13 分钟前
Spring Boot:别再重复造轮子,这些内置功能香麻了
后端
青山师14 分钟前
Java注解深度解析:从元数据机制到框架开发基石
java·开发语言·注解·javase·java面试·后端开发·java核心
tonydf16 分钟前
快速上手AI网关——LiteLLM
后端·aiops
Pkmer16 分钟前
类的封装性: 让门面设计模式来打开这扇门
后端·设计模式