Scala文件读写-全文单词统计1.0

37 阅读1分钟

任务分析

  1. 把文字内容从.txt文件中读到内存中。

  2. 写程序分析数据。

  3. 把结果写入.txt文件。

在scala中,涉及到文件读写的方法有很多,可以使用java.io下的工具包,也可以使用scala.io下的功能。

下面介绍source.fromFile这个方法。

格式:scala.io.Source.formFile(文件名)

作用:读入一个文件

注:src 与 txt文件在同一目录下

image.png

写拆分单词统计个数

思路:

1. 分隔出一个一个的单词。

2. 建立一个Map,key是单词,value是次数。

3. 遍历所有的单词,对每个单词来说:

判断单词是否存在,如果存在把对应的key+1;

否则就设置对应的key,且value为1

package words

object words01 {
  def main(args: Array[String]): Unit = {
    val content = scala.io.Source.fromFile("test.txt").mkString;

    // 2. 把字符串拆分为单词
    val list = content.split(" "); // 使用 空格 去拆分字符串;结果是一个List
    // list.foreach(ele => println(ele))

    // 3. 统计每个单词出现的次数
    // 新建一个Map("I" -> 1, "am" -> 2)
    val map1 = scala.collection.mutable.Map("I" -> 0)
    // 对于list中的每个单词,
    list.foreach(word => {
    // 检查它在Map中是否存在?
    // println(word, map1.contains(word))
      if (map1.contains(word)) {
        map1(word) += 1 // 存在:把它的值+1
      } else {
        map1(word) = 1 // 不存在:把它的值设为1
      }
    })

    map1.foreach(el => println(el))
  }
}