我正在嘗試讀取CSV並將其存儲在陣列對象的矩陣狀數組中。我碰到的一個障礙是,字符串在和中被讀出 - 也就是說,字符串「price」不僅僅是價格,而是scala中的「」「」price「」「」。因此,我想刪除那些周圍的引號。我也想確保任何數值被強制爲Double/Int,因爲它們是以字符串形式讀入的。格式化讀入CSV數據
我現在擁有的一切:
val rawObs = io.Source.fromFile(file).getLines() .map(_.split(",")).toArray
// An example element of the array is:
//scala> rawObs(2)
//res93: Array[String] = Array("3", 0, "2013-02-27", 1, 52, 52, 1, "1", "kg")
// Here, I make a function to remove surrounding strings and return a string, or if there are
// not surrounding strings, return a Double.
def fixRawObs(x: String) = {
// if it was actually meant to be a string:
if(x.startsWith(""""""")){
// delete any " quotes
var y = x.replaceAll(""""""", "")
} else { // this means that x needs to be coerced to Int or Double
var y = x.toDouble
}
y // return y
}
// but this won't compile, it returns <console>:14: error: not found: value y
// If it did compile, I'd want to do something like this:
rawObs.map(_.map(fixRawObs(_)))
// (although, is there a better way?)
所以,基本上,我的第一個問題是如何解決我fixRawObs功能,其次,這是甚至一個好辦法做到這一點,還是有一些更好的方式來完成我想要的?我在做什麼感覺有點ha。。
我是超級新來的斯卡拉,所以它將不勝感激,如果答案不承擔太多的知識。謝謝!
謝謝!信息豐富,非常有幫助。唯一讓這個有點不理想的是CSV類型(String,Double,String,...)被硬編碼,所以如果CSV的格式略有改變,這將會中斷。 –