【问题标题】:Reading a collection of lists from file in scala从scala中的文件中读取列表集合
【发布时间】:2013-08-13 05:54:51
【问题描述】:

我想阅读一个包含两列整数的大文本文件。对于第一列不变的每个连续拉伸,我想将第二列收集为列表。例如,以下示例

1 2
1 1
1 2
4 3
4 8
1 5
8 2
8 2
8 7

应该生成列表

2,1,2
3,8
5
2,2,7

在 Scala 中实现这一目标的正确方法是什么?

特别是,如果有一个“惰性”解决方案会非常好,这样我就可以处理每个列表,而不必先将整个文件加载到内存中。

【问题讨论】:

    标签: scala io


    【解决方案1】:
    val nums = """(\d+) (\d+)""".r
    
    val tuples = io.Source.fromFile("list.txt").getLines collect {
      case nums(label, num) => (label.toInt -> num.toInt)
    }
    
    def toList(tuples: Iterator[(Int, Int)]): Iterator[Seq[Int]] = {
      if(!tuples.hasNext) Iterator.empty
      else {
        val (label, num) = tuples.next
        val (succ, rest) = tuples.span(_._1 == label)
        Iterator(num :: succ.map(_._2).toList) ++ toList(rest)
      }
    }
    
    toList(tuples)foreach(println)
    

    【讨论】:

      【解决方案2】:

      最简单的方法是使用scala.io.Source逐行读取文件。使用getLines,您可以检索Iterator[String],您可以在其上映射以拆分行并将它们转换为整数,如下所示:

      val intPairs = Source.fromFile("/path/to/file").getLines.map { line =>
        line.split(" ").take(2).map(_.toInt)
      }
      

      我将连续行的分组留给你作为练习。

      【讨论】:

        猜你喜欢
        • 2012-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        相关资源
        最近更新 更多