2012-01-16 64 views
1

我很難包裝我的頭周圍如何解析一個csv文件並將其張貼到web服務使用scala。需要幫助,試圖解析文件和創建scala地圖

基本思路是我需要從csv文件創建後參數。標題將是參數,下面的行將是值,即。

例如CSV

firstname, lastname, age, weight, height 
John, Doe, 30, 180, 72 
Mary, Jane, 28, 120, 64 

這將映射到參數 firstname=John&lastname=Doe&age=30&weight=180&height=72

我有以下階分析數據,但似乎無法找出下一步做什麼:

val lines = fromFile("runners/io/m2m/naf/ARDS.csv").getLines 
     for ((line, cnt) <- lines.zipWithIndex) { 
     if (cnt == 0) { 
      for((header, i) <- CsvParser.parse(line).view.zipWithIndex){ 

      } 
     }else { 
      for((data, i) <- CsvParser.parse(line).view.zipWithIndex) { 

      } 
     } 
     } 
+0

店頭在由'i'索引的映射,然後爲每個'data'項,查找地圖並輸出header = data。需要更多幫助? – milan 2012-01-16 19:03:53

+0

是的我想我可以使用不可變的地圖等,但它似乎應該有一個功能的方法來解決這個問題。 – chiappone 2012-01-16 19:13:10

+0

哦,它沒有在問題中指定,你正在尋找一個'功能的方法'.. – milan 2012-01-16 19:14:13

回答

6

這個怎麼樣?

val lines = fromFile("runners/io/m2m/naf/ARDS.csv").getLines 
val header = CsvParser.parse(lines.next) 
val rowMapsIterator = 
    for (line <- lines) 
    yield (header zip CsvParser.parse(line)).toMap 

那麼結果如下:

scala> for((map, cnt) <- rowMapsIterator.zipWithIndex) println(cnt + ": " + map) 
0: Map(firstname -> John, weight -> 180, lastname -> Doe, age -> 30, height -> 72) 
1: Map(firstname -> Mary, weight -> 120, lastname -> Jane, age -> 28, height -> 64) 

要獲得& - 分隔格式,你反而會做:

val rowStringIterator = rowMapsIterator.map(_.map { case (k, v) => k + "=" + v }.mkString("&")) 

這給了你:

scala> for ((s, cnt) <- rowStringIterator.zipWithIndex) println(cnt + ": " + s) 
0: weight=180&firstname=John&height=72&age=30&lastname=Doe 
1: weight=120&firstname=Mary&height=64&age=28&lastname=Jane 
+0

永遠不知道有這樣的事情拉鍊。很感謝。 – chiappone 2012-01-17 00:48:00

0

我用dhg的a nswer,但是將列表扁平化,因爲CsvParser正在返回一個List [List []]。

因此 -

val header = CsvParser.parse(lines.next).flatten 


val rowMapsIterator = 
| for (line <- lines) 
|  yield (header zip CsvParser.parse(line).flatten).toMap 

這給了我地圖的標題欄的數據列映射

scala> rowMapsIterator.foreach(println) 
Map(weight -> 180, firstname -> John, height -> 72, age -> 30, lastname -> Doe) 
Map(weight -> 120, firstname -> Mary, height -> 64, age -> 28, lastname -> Jane)