1 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是如何完成的基本概述。
val keywords = List(/*key words here*/)
val resMap = io.Source
.fromFile(/*file to read*/)
.getLines()
.zipWithIndex
.foldLeft(Map.empty[String,Seq[Int]].withDefaultValue(Seq.empty[Int])){
case (m, (line, idx)) =>
val subMap = line.split("\\W+").toSeq //separate the words
.filter(keywords.contains) //keep only key words
.groupBy(identity) //make a Map w/ keyword as key
.mapValues(_.map(_ => idx+1)) //and List of line numbers as value
.withDefaultValue(Seq.empty[Int])
keywords.map(kw => (kw, m(kw) ++ subMap(kw))).toMap
}
//formatted results (needs work)
println("keyword\t\tlines\t\tcount")
keywords.sorted.foreach{kw =>
println(kw + "\t\t" +
resMap(kw).distinct.mkString("[",",","]") + "\t\t" +
resMap(kw).length
)
}
一些解釋
io.Source
object
是提供一些基本輸入/輸出方法的庫(實(shí)際上是一個(gè)),包括fromFile()
打開一個(gè)文件以供閱讀。getLines()
一次從文件中讀取一行。zipWithIndex
將索引值附加到讀取的每一行。foldLeft()
一次讀取文件的所有行,并且(在這種情況下)構(gòu)建Map
所有關(guān)鍵字及其行位置的 a。resMap
并且subMap
只是我選擇給我正在構(gòu)建的變量的名稱。resMap
(result Map) 是在處理整個(gè)文件后創(chuàng)建的。subMap
是由文件中的一行文本構(gòu)建的中間 Map。
如果您想選擇傳遞一組關(guān)鍵詞,我會(huì)這樣做:
val keywords = if (args.length > 1) args.tail.toList else hardcodedkeywords
添加回答
舉報(bào)