Scala 统计文件单词数

本文通过具体示例详细解析了Scala中的foldLeft函数,并演示了如何利用该函数进行文本处理,包括读取文件、字符串清洗及词频统计等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数原型:

def foldLeft[B](z: B)(op: (B, A) => B): B = {
    var result = z
    this.seq foreach (x => result = op(result, x))
    result
  }


实现代码:

val lines = Source.fromFile("E://test.txt").getLines()
    val seqop = (result: mutable.HashMap[String, Int], line: String) => {
    val wordcount = line.replace(",", " ").replace(".", " ").replace("(", " ").replace(")", " ").split(" ").filter(_.trim.length > 0).map(word => (word, 1))
    wordcount.foreach(wc => {
        val addOne = (wc._1, result.getOrElse(wc._1, 0) + wc._2)
        result += addOne
      })
      result
    }
    val combop = (result1: mutable.HashMap[String, Int], result2: mutable.HashMap[String, Int]) => {
      result1 ++= result2
    }
     val test =  lines.foldLeft(new mutable.HashMap[String, Int]())(seqop)


    println(test)


文件内容:

one one two
one two three
four two three


运行结果:

Map(one -> 3, three -> 2, four -> 1, two -> 3)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值