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

}
相关推荐
君顾15 分钟前
折扣卡 CPS 小程序定制:从业务流程到系统架构的实践指南
java·开发语言·折扣卡
江湖十年17 分钟前
Go 还是 Golang?可能你一直都搞错了!
后端·面试·go
计算机毕设定制辅导-无忧学长25 分钟前
《基于SpringBoot的庭院玫瑰栽培养护知识交互式科普平台设计与实现》
java·spring boot·后端·毕业设计·个性化推荐·协同过滤算法·庭院玫瑰栽培养护知识科普平台
骇客野人27 分钟前
SpringBoot数十Jar包批量生产部署落地实施方案(Shell+Systemd完整版)
spring boot·后端·jar
坚定学代码1 小时前
static在c++中的使用
开发语言·c++
Json____1 小时前
从零构建家政服务平台:一套全栈架构如何打通管理端与移动端-java-springboot
java·spring boot·后端·架构·毕设·wwwoop.com
leeyi1 小时前
命令行里的平台:df_cli 都会什么(第108篇)
后端·aigc·agent
云雀衔光2 小时前
Java Spring AI MCP:在 Spring 里把 AI 接上你的业务系统
java·开发语言·人工智能·后端·测试工具·spring
重生之小比特2 小时前
【Java SE】数据类型与变量
java·开发语言·python
苏渡苇2 小时前
Spring Insight 里如何对 Span 进行清洗
java·spring boot·后端·spring·系统监控