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

}
相关推荐
To_OC6 小时前
手写 AI 编程 Agent 的命令执行工具:我被 child_process 坑出来的实战经验
后端·node.js·agent
科技道人6 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
逝水无殇8 小时前
C# 异常处理详解
开发语言·后端·c#
玖玥拾10 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
铅笔侠_小龙虾10 小时前
Rust 学习目录
开发语言·学习·rust
考虑考虑11 小时前
Sentinel安装
java·后端·微服务
IT_陈寒11 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端
云泽80811 小时前
从零吃透 C++ 异常:抛出捕获、栈展开、异常重抛与编码规范详解
开发语言·c++·代码规范
碎碎念_49211 小时前
SpringBoot + Vue 前后端分离从 0 到 1 完整环境配置流程
vue.js·spring boot·后端
灯澜忆梦11 小时前
GO---可见性规则
开发语言·golang