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()//关闭
  }
}
相关推荐
朱嘉鼎8 小时前
C语言之可变参函数
c语言·开发语言
北冥湖畔的燕雀10 小时前
C++泛型编程(函数模板以及类模板)
开发语言·c++
QX_hao12 小时前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白12 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
Evand J14 小时前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
爱喝白开水a15 小时前
LangChain 基础系列之 Prompt 工程详解:从设计原理到实战模板_langchain prompt
开发语言·数据库·人工智能·python·langchain·prompt·知识图谱
Neverfadeaway15 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
武子康15 小时前
Java-152 深入浅出 MongoDB 索引详解 从 MongoDB B-树 到 MySQL B+树 索引机制、数据结构与应用场景的全面对比分析
java·开发语言·数据库·sql·mongodb·性能优化·nosql
杰克尼15 小时前
JavaWeb_p165部门管理
java·开发语言·前端
一成码农15 小时前
JavaSE面向对象(下)
java·开发语言