0
我有一個文檔列表,我想查找所有文檔中的(term -> termCount)
對。這裏是我正在做它:Scala foldLeft地圖和文檔的termCount
object termCount extends App {
val docs = List(
List("A", "B", "C", "C"),
List("A", "D"),
List("B", "B", "C"))
val countsMap = docs.flatMap { ts =>
val m = ts.map((_, 1)).groupBy(_._1)
m.map { e => e._1 -> e._2.foldLeft(0)(_ + _._2) }
}.groupBy(_._1)
.map { e => e._1 -> e._2.foldLeft(0)(_ + _._2) }
println(countsMap)
}
OUTPUT:
Map(D -> 1, A -> 2, C -> 3, B -> 3)
把它分解成操作,我在做什麼是:
產生的
元組(term, 1)
val m = ts.map((_, 1)).groupBy(_._1)
計算文檔本地termCount
e => e._1 -> e._2.foldLeft(0)(_ + _._2)
生成文檔本地
(term -> termCount)
項所有文檔壓扁這個地圖回元組
(term, termCount)
的Map
也再次做了
foldLeft
獲得全球termcounts
我的問題是,我怎樣才能讓這段代碼更簡潔?