scala 计算读取文件中包含的列表中的字符串

scala count strings in a list contained in a read file

我是 SO 的新手,但花了好几天时间来解决相关问题。我发现的最接近的相关问题是 How to compare each word of a line in a file with a list element in scala?,但这可以追溯到 2014 年,所以我认为现在可能有不同的解决方案。

同样在上面引用的 post 中,最佳答案使用了我试图避免的可变数据结构。 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),要读取的文件,并将其映射到一个列表,其中每行包含一个字符串以及 index+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 是一个库(实际上是一个 object),它提供了一些基本的 input/output 方法,包括 fromFile(),它可以打开文件进行读取。
  • getLines() 从文件中一次读取一行。
  • zipWithIndex 为读取的每一行附加一个索引值。
  • foldLeft() 读取文件的所有行,一次一行,并且(在本例中)构建所有关键字及其行位置的 Map
  • resMapsubMap 只是我为正在构建的变量选择的名称。 resMap (result Map) 是整个文件被处理后创建的。 subMap 是仅由文件中的一行文本构建的中间地图。

如果你想要传递一组关键词的选项,我会这样做:

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