【发布时间】:2019-12-01 23:10:48
【问题描述】:
val keywords = List("do", "abstract","if")
val resMap = io.Source
.fromFile("src/demo/keyWord.txt")
.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
}
println("keyword\t\tlines\t\tcount")
keywords.sorted.foreach{kw =>
println(kw + "\t\t" +
resMap(kw).distinct.mkString("[",",","]") + "\t\t" +
resMap(kw).length)
}
此代码不是我的,我不拥有它......用于学习目的。但是,我仍在学习,并且我被困在实现连续到非连续列表中,例如“if”一词在多行中,当出现三个或更多连续行号时,它们之间应该用破折号书写,例如20-22,但不是 20、21、22。我该如何实施?我就是想学这个。
输出:
keyword lines count
abstract [1] 1
do [6] 1
if [14,15,16,17,18] 5
但我希望结果类似于 [14-18] 因为单词“if”在第 14 到 18 行。
【问题讨论】: