读取文件并将元素存储为数组Scala

时间:2017-03-30 17:26:56

标签: arrays scala file

我是Scala的新手,这是我第一次使用它。我想在带有两列数字的文本文件中读取,并将每个列项存储在一个单独的列表或数组中,这些列或数组必须转换为整数。例如,文本文件如下所示:

1 2 
2 3 
3 4 
4 5 
1 6 
6 7 
7 8 
8 9 
6 10 

我想将两列分开,以便每列都存储在其列表或数组中。

2 个答案:

答案 0 :(得分:0)

这是一种可行的方法:

val file: String = ??? // path to .txt in String format
val source = Source.fromFile(file)

scala> val columnsTogether = source.getLines.map { line =>
  val nums = line.split(" ") // creating an array of just the 'numbers'
  (nums.head, nums.last) // assumes every line has TWO numbers only
}.toList
columnsTogether: List[(String, String)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (6,7), (7,8), (8,9), (6,10))

scala> columnsTogether.map(_._1.toInt)
res0: List[Int] = List(1, 2, 3, 4, 1, 6, 7, 8, 6)

scala> columnsTogether.map(_._2.toInt)
res1: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)

答案 1 :(得分:0)

假设您将该文件命名为“列”,这将是一个解决方案:

    val lines = Source.fromFile("columns").getLines() 
    /* gets an Iterator[String] which interfaces a collection of all the lines in the file*/
    val linesAsArraysOfInts = lines.map(line => line.split(" ").map(_.toInt)) 
    /* Here you transform (map) any line to arrays of Int, so you will get as a result an Interator[Array[Int]] */ 
    val pair: (List[Int], List[Int]) = linesAsArraysOfInts.foldLeft((List[Int](), List[Int]()))((acc, cur) => (cur(0) :: acc._1, cur(1) :: acc._2))
    /* The foldLeft method on iterators, allows you to propagate an operation from left to right on the Iterator starting from an initial value and changing this value over the propagation process. In this case you start with two empty Lists stored as Tuple an on each step you prepend the first element of the array to the first List, and the second element to the second List. At the end you will have to Lists with the columns in reverse order*/

    val leftList: List[Int] = pair._1.reverse
    val rightList: List[Int] = pair._2.reverse
    //finally you apply reverse to the lists and it's done :)