Scala全文单词统计

一:方法

复制代码
package test5
import java.io.PrintWriter
import scala.io.Source
//可变的Map
import scala.collection.mutable
object test5_1 {
  def main(args: Array[String]): Unit = {
//1.读入文件
    val content = Source.fromFile("1.txt").mkString
//    println(content)

    //2.拆分字符串-->单词数组
//    val rs = content.split(",")正则表达式
//    W:表示非字符(,空格,?...)
//    W+:多个非字符
    val rs = content.split("\\w+")
//    println("-"*40)
//    rs.foreach(println)

    //3.统计出现的频率
    val wordsMap = mutable.Map[String,Int]()
    rs.foreach(w => {
      val word = w.toLowerCase()//全小写
      //是否出现
      if(wordsMap.contains(word)){
        wordsMap(word)+=1
      }else{
        wordsMap(word) = 1
      }
    })
    //4.根据出现的次数从高到低排序
    //Map不能直接排序,需要转成有序的集合
    val orderList = wordsMap.toList.sortWith((a,b)=>a._2>b._2)
    //输出Map

    //5.保存结果,涉及到写入文件
    val writer = new PrintWriter("output.txt")

    for (e<- orderList){
      println(e._1,e._2)
      writer.println(s"${e._1}:${e._2}次")

    }
    writer.close()//关闭
  }
}
相关推荐
两点王爷7 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
微笑星河q9 小时前
C++高阶之【多态】
开发语言·c++
ClkLog-开源埋点用户分析12 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言
yuzhiboyouye13 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql
郝学胜-神的一滴13 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
geovindu13 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
时间的情敌15 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu1213816 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
敲上瘾17 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3