Simplest way to count words in a file
scala
Solution
You can turn the file lines into words by splitting them with the regex `"\\W+"` (`flatmap` is lazy so it doesn't need to load the entire file into memory). To count occurrences you can fold over a `Map[String, Int]` updating it with each word (much more memory and time efficient than using `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))
}
Problem
I'm trying to code in the simplest way a program to count word occurrences in file in Scala Language. So far I have these piece of code: ``` 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) } } ``` Don't bother of regexp expression. I would like to know how to extract single words from sequence retrieved in this line: ``` map(l => Word.findAllIn(l.toLowerCase()).toSeq) ``` in order to get each word occurency counted. Currently I'm getting map with counted words sequences.