如何将csv文件读入scala中的数组数组 [英] How to read csv file into an Array of arrays in scala
问题描述
我正在尝试读取一个csv文件,并将其作为双精度数组(Array[Array[Double]]
)的数组返回.很明显,如何逐行读取文件并立即将其打印出来,但是如何将其存储在二维数组中却很清楚.
I'm trying to read a csv file and return it as an array of arrays of doubles (Array[Array[Double]]
). It's pretty clear how to read in a file line by line and immediately print it out, but not how to store it in a two-dimensional array.
def readCSV() : Array[Array[Double]] = {
val bufferedSource = io.Source.fromFile("/testData.csv")
var matrix :Array[Array[Double]] = null
for (line <- bufferedSource.getLines) {
val cols = line.split(",").map(_.trim)
matrix = matrix :+ cols
}
bufferedSource.close
return matrix
}
遇到了一些类型问题,然后意识到我没有按照我想做的去做.向我指出正确方向的任何帮助将不胜感激.
Had some type issues and then realized I'm not doing what I thought I was doing. Any help pointing me on the right track would be very appreciated.
推荐答案
似乎您的问题已得到回答.因此,作为旁注,您可以像下面这样更加隐蔽地编写代码:
It seems your question was already answered. So just as a side note, you could write your code in a more scalaish way like this:
def readCSV() : Array[Array[Double]] = {
io.Source.fromFile("/testData.csv")
.getLines()
.map(_.split(",").map(_.trim.toDouble))
.toArray
}
这篇关于如何将csv文件读入scala中的数组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!