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

}

}

相关推荐
cypking11 小时前
三、前端规范化 项目代码规范
前端·代码规范
m0_7482546614 小时前
Perl 变量类型
spark·scala·perl
码界奇点15 小时前
基于Spring MVC的缺陷管理系统设计与实现
java·spring·车载系统·毕业设计·mvc·源代码管理
码界奇点18 小时前
基于Spring Boot 3与UniApp的跨平台新零售电商系统设计与实现
spring boot·uni-app·毕业设计·uniapp·零售·源代码管理
HellowAmy1 天前
我的C++规范 - 跳跃的对象
开发语言·c++·代码规范
南山安1 天前
TypeScript:更加安全规范的JavaScript
react.js·typescript·代码规范
donecoding1 天前
Sass 模块化革命:告别 @import,拥抱 @use 和 @forward
前端·css·代码规范
爱学java的ptt2 天前
线程池简单源码思路手撕实现和关于参数设置
源代码管理
donecoding2 天前
AI时代程序员的护城河:让AI做创意组合,用标准化工具守住质量底线
javascript·架构·代码规范
donecoding2 天前
CSS的"双胞胎"陷阱:那些看似对称却暗藏玄机的属性对
前端·css·代码规范