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()//结束写入
  }

}
相关推荐
一方热衷.2 小时前
YOLO26-Seg ONNXruntime C++/python推理
开发语言·c++·python
靓仔建3 小时前
Vue3导入组件出错does not provide an export named ‘user_setting‘ (at index.vue:180:10)
开发语言·前端·typescript
凤山老林3 小时前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
清汤饺子3 小时前
用 Cursor 半年了,效率还是没提升?是因为你没用对这 7 个功能
前端·后端·cursor
雨夜之寂4 小时前
Browser Use + DeepSeek,我踩了哪些坑
后端·面试
wefly20174 小时前
开发者效率神器!jsontop.cn一站式工具集,覆盖开发全流程高频需求
前端·后端·python·django·flask·前端开发工具·后端开发工具
赶路人儿4 小时前
UTC时间和时间戳介绍
java·开发语言
dreamread4 小时前
【SpringBoot整合系列】SpringBoot3.x整合Swagger
java·spring boot·后端
6+h4 小时前
【java】基本数据类型与包装类:拆箱装箱机制
java·开发语言·python
把你毕设抢过来4 小时前
基于Spring Boot的社区智慧养老监护管理平台(源码+文档)
数据库·spring boot·后端