我正在尝试以最简单的方式编写一个程序来计算 Scala 语言文件中单词出现的次数。到目前为止我有这些代码:
import scala.io.Codec.string2codec
import scala.io.Source
import scala.reflect.io.File
object WordCounter {
val SrcDestination: String = ".." + File.separator + "file.txt"
val Word = "\\b([A-Za-z\\-])+\\b".r
def main(args: Array[String]): Unit = {
val counter = Source.fromFile(SrcDestination)("UTF-8")
.getLines
.map(l => Word.findAllIn(l.toLowerCase()).toSeq)
.toStream
.groupBy(identity)
.mapValues(_.length)
println(counter)
}
}
不要担心正则表达式。我想知道如何从中提取单个单词
在此行中检索到的序列:
map(l => Word.findAllIn(l.toLowerCase()).toSeq)
为了得到每个单词出现的次数。目前我正在获取带有计数单词序列的地图。
您可以通过使用正则表达式将文件行拆分为单词"\\W+"
(flatmap
是惰性的,因此不需要将整个文件加载到内存中)。要计算出现次数,您可以折叠Map[String, Int]
用每个单词更新它(比使用更节省内存和时间)groupBy
)
scala.io.Source.fromFile("file.txt")
.getLines
.flatMap(_.split("\\W+"))
.foldLeft(Map.empty[String, Int]){
(count, word) => count + (word -> (count.getOrElse(word, 0) + 1))
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)