1 回答

TA贡献1719条经验 获得超6个赞
这是如何完成的基本概述。
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
是提供一些基本输入/输出方法的库(实际上是一个),包括fromFile()
打开一个文件以供阅读。getLines()
一次从文件中读取一行。zipWithIndex
将索引值附加到读取的每一行。foldLeft()
一次读取文件的所有行,并且(在这种情况下)构建Map
所有关键字及其行位置的 a。resMap
并且subMap
只是我选择给我正在构建的变量的名称。resMap
(result Map) 是在处理整个文件后创建的。subMap
是由文件中的一行文本构建的中间 Map。
如果您想选择传递一组关键词,我会这样做:
val keywords = if (args.length > 1) args.tail.toList else hardcodedkeywords
添加回答
举报