我正在尝试以最简单的方式编写一个程序来计算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)
}
}
Run Code Online (Sandbox Code Playgroud)
不要打扰正则表达式.我想知道如何从此行中检索的序列中提取单个单词:
map(l => Word.findAllIn(l.toLowerCase()).toSeq)
Run Code Online (Sandbox Code Playgroud)
为了得到每个单词的出现次数.目前我正在使用计算单词序列的地图.
Gar*_*all 35
您可以通过使用正则表达式将文件行拆分为单词"\\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))
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*obi 15
我认为以下内容稍微容易理解:
Source.fromFile("file.txt").
getLines().
flatMap(_.split("\\W+")).
toList.
groupBy((word: String) => word).
mapValues(_.length)
Run Code Online (Sandbox Code Playgroud)