大数据全系列 教程
1869个小节阅读:464.8k
目录
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
单词文件wc.txt,内容如下:
xxxxxxxxxx
hello tom
andy joy
hello rose
hello joy
mark andy
hello tom
andy rose
hello joy
通过学过的集合常用方法,统计每个单词出现的次数。
首先在当前项目下创建目录input,然后在创建wc.txt文件,打开该文件,将上面的数据添加到该文件中。
接下来编码实现:
xxxxxxxxxx
package com.itbaizhan.chapter07
import scala.io.{BufferedSource, Source}
//单词统计
object WordCount {
def main(args: Array[String]): Unit = {
//TODO 1.读取文件
val bufferedSource: BufferedSource = Source.fromFile("input/wc.txt")
//TODO 2.读取文件中所有的行
val lines: Iterator[String] = bufferedSource.getLines()
//TODO 3.将lines转换为List对象
val linesList: List[String] = lines.toList
//println(linesList)
//TODO 4.使用扁平化函数flatMap 将每行的内容拆分开成一个个的单词
val wordsList: List[String] = linesList.flatMap(_.split(" "))
//TODO 5.使用功能函数map将之映射为 每个单词->1
val word2OneList: List[(String, Int)] = wordsList.map((_,1))
//println(word2OneList)//List((hello,1), (tom,1), (andy,1), (joy,1),...)
//TODO 8.过滤掉单词为空格的垃圾数据
/*var word2OneList: List[(String, Int)] = wordsList.map((_,1))
//val tuples: List[(String, Int)]
word2OneList = word2OneList.filter(
keyValue => { //(hello,1)
if (keyValue._1 != null && !keyValue._1.trim.isEmpty) {
true
} else {
false
}
}
)*/
//TODO 6.使用功能函数groupBy将相同的单词分为一组
val wordGroupMap: Map[String, List[(String, Int)]] = word2OneList.groupBy(_._1)
//println(wordGroupMap)//Map(tom -> List((tom,1), (tom,1)), ...)
val wordCountMap: Map[String, Int] = wordGroupMap.map(
keyVal => {//keyVal为一个二元组
//_1 对应单词tom;_2对应List((tom,1), (tom,1)),List.size就是单词出现的总次数
(keyVal._1, keyVal._2.size)
}
)
//Map(tom -> 2, joy -> 3, andy -> 3, hello -> 5, mark -> 1, rose -> 2)
println(wordCountMap)
//TODO 7.如果wc.txt文件中出现多余的空格(修改wc.txt文件最后一行"hello joy"->"hello joy")
//将两个单词中一个空格改为三个空格的话,再次运行程序:Map( -> 2, tom -> 2,...)
// 发现 空格也被统计到里面了,如果过滤掉空格呢? -> 8(在步骤5后面)
}
}