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

}
相关推荐
追逐时光者4 小时前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
TF男孩4 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥5 小时前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
AAA修煤气灶刘哥6 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
你的人类朋友6 小时前
什么是API签名?
前端·后端·安全
昵称为空C8 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默8 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin9 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在9 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit9 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言