我是SO的新手,但是花了很多天与问题相关.我发现的最接近的相关问题是How to compare each word of a line in a file with a list element in scala?,但该问题可以追溯到2014年,因此认为现在可能会有不同的解决方案.

 

同样在以上引用的帖子中,最佳答案使用了一个可变的数据结构,我试图避免这种结构. Dima的最后一个答案看起来更实用,但是没有用:(

我正在尝试在SCALA中创建一个类似的程序,除了输出还应该包含关键字的总计数,并且应该输出所有关键字,即使没有找到匹配项,因此计数也将为零.

要检查的关键字被硬编码到列表中,但是我还想添加包含关键字的第二个用户提供的参数选项.到目前为止,我来了以下内容,但是很烂:

 

object FileAnalyser extends App {

val hardcodedkeywords = List("foo", "bar", "hello")

if (args.length > 1) {
  val keywords = args(1).toList
  try {
    val rdd = Source.fromFile(args(0)).getLines.toList.zipWithIndex.flatMap {
      case(line, index) => line.split("\\W+").map { (_, index+1) }
    } //.filter(keywords.contains(_)).groupBy { _._1 }.mapValues(_._2)
  } catch {
    case ioe: IOException => println(ioe)
    case fnf: FileNotFoundException => println(fnf)
    case _: Throwable => println("Uknown error occured")
  }
} else 
  try {
    val rdd = Source.fromFile(args(0)).getLines.toList.zipWithIndex.flatMap {
      case(line, index) => line.split("\\W+").map { (_, index+1) }
    } //filter(hardcodedkeywords.contains(_))
      //.groupBy { _._1 }.mapValues(_._2)
  } catch {
    case ioe: IOException => println(ioe)
    case fnf: FileNotFoundException => println(fnf)
    case _: Throwable => println("Uknown error occured")
  }
}

到目前为止,我设法使用了包含要读取,要读取的文件的args(0),并将其映射到每行包含一个字符串以及索引1的列表(因为行号从1开始,但索引从0开始)
该程序必须具有尽可能好的功能,以使可变性和状态更改更少,而更高阶的功能和列表递归.

谢谢
输出示例如下:

 

//alphabetical      //No duplicates
//order             //Increasing in no. 
keyword              lines                count
bar                  [1,2..]                6
foo                  [3,5]                  2
hello                []                     0

最佳答案

这是如何完成的基本概述.

 

 

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是提供一些基本输入/输出方法的库(实际上是一个对象),其中包括fromFile(),该方法打开一个文件以供读取.
> getLines()一次从文件读取一行.
> zipWithIndex将索引值附加到每个读取的行.
> foldLeft()一次读取文件的所有行,并且(在这种情况下)构建所有关键字及其行位置的Map.
> resMap和subMap只是我选择为要构建的变量命名的名称. resMap(结果图)是在处理了整个文件之后创建的. subMap是仅根据文件中的一行文本构建的中间Map.

如果您希望传递一组关键字,可以这样:

 

val keywords = if (args.length > 1) args.tail.toList else hardcodedkeywords