从文件中读出文件
在scala中,涉及到文件读写的方法有很多,可以使用java.io下的工具包,也可以使用scala.io下的功能。
读出文件的格式
格式:scala.io.Source.formFile(文件名)
基本代码
package words
object words01 {
def main(args: Array[String]): Unit = {
//1. 读入 test.txt 的内容 大大的,长长的字符串
// Source.formFile.mkString
//2. 对字符串进行拆分 把句子变成一个一个单词
// split
// 1
val content=scala.io.Source.fromFile("./test.txt").mkString
println(content)
// 2. 对字符串进行拆分
val rst = content.split(' ')
//["I","like","scala"]
rst.foreach(println)
}
}
写拆分单词统计个数
基本代码
package words
object words01 {
def main(args: Array[String]): Unit = {
//1. 读入 test.txt 的内容 大大的,长长的字符串
// Source.formFile.mkString
//2. 对字符串进行拆分 把句子变成一个一个单词
// split
// 1
val content=scala.io.Source.fromFile("./test.txt").mkString
println(content)
// 2. 对字符串进行拆分:使用split空格,对这个长长的字符串做拆分,得到了一个数组,每个元素都是一个单词
val rst = content.split(' ')
//["I","like","scala"]
// rst.foreach(println)
// 3. 空的容器保存键值对数据: 键:单词 值:次数
val map=scala.collection.mutable.Map[String,Int]()
rst.foreach(word => {
//如果word在map中存在,就把值+1
if(map.contains(word)){
map(word) += 1
}
else{ //如果word在map中不存在,就把值设为1
//map += word ->1
map(word) = 1
}
// 4. 打印统计结果
map.foreach(println)
})
}
}
对Map结果排序以及结果写入
基本代码
package words
import java.io.FileWriter
object words01 {
def main(args: Array[String]): Unit = {
//1. 读入 test.txt 的内容 大大的,长长的字符串
// Source.formFile.mkString
//2. 对字符串进行拆分 把句子变成一个一个单词
// split
// 1
val content=scala.io.Source.fromFile("./test.txt").mkString
println(content)
// 2. 对字符串进行拆分:使用split空格,对这个长长的字符串做拆分,得到了一个数组,每个元素都是一个单词
// \W+ 正则表达式,W表示一个非字符(空格,符号,!。:;) +表示一个及以上
// map 把每个单词都变小写
val rst = content.split("\W+").map(ele =>ele.toLowerCase)
//["I","like","scala"]
// rst.foreach(println)
// 3. 空的容器保存键值对数据: 键:单词 值:次数
val map=scala.collection.mutable.Map[String,Int]()
rst.foreach(word => {
//如果word在map中存在,就把值+1
if(map.contains(word)){
map(word) += 1
}
else{ //如果word在map中不存在,就把值设为1
//map += word ->1
map(word) = 1
}
// 4. 打印统计结果
// map.foreach(println)
//按照单词出现的频率,从高到低排序
//map是无序的,不能做排序
//list是可以排序的
val wordList=map.toList.sortBy(_._2).reverse
// 5. 把结果写入到文件中
val writer=new FileWriter("result.txt")
wordList.foreach(ele => {
writer.write(s"${ele._1}: ${ele._2} \n")
})
writer.close()
})
}
}
结果输出为:
the: 9
a: 5
i: 4
my: 4
that: 4
on: 3
to: 2
and: 2
stream: 2
tune: 2
this: 2
woods: 2
like: 2
in: 2
blows: 2
leaves: 2
path: 2
smile: 2
listen: 2
through: 2
walk: 1
under: 1
step: 1
carries: 1
s: 1
fallen: 1
with: 1
calm: 1
precious: 1
mind: 1
lovely: 1
quiet: 1
whispers: 1
of: 1
winds: 1
flows: 1
sounds: 1
world: 1
hair: 1
moment: 1
pine: 1
sings: 1
feels: 1
crunch: 1
child: 1
wind: 1
lingers: 1
gently: 1
light: 1
stop: 1
heart: 1
feeling: 1
gurgles: 1
all: 1
soft: 1
day: 1
because: 1
bird: 1
nearby: 1
smell: 1
simple: 1
happy: 1
feet: 1
hum: 1
gift: 1