函数原型:
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)
Scala折左函数解析
本文通过具体示例详细解析了Scala中的foldLeft函数,并演示了如何利用该函数进行文本处理,包括读取文件、字符串清洗及词频统计等操作。
2681

被折叠的 条评论
为什么被折叠?



