我很难解决如何解析csv文件并使用scala将其发布到web服务。
基本思路是我需要从csv文件创建post params。标题将是参数,以下行将是值。
示例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
等。
我有以下scala来解析数据,但似乎无法弄清楚下一步该做什么:
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 :(得分: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)
要获得这种&amp; -separated格式,您可以改为:
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
答案 1 :(得分:0)
我使用了dhg的答案,但是平了列表,因为CsvParser正在回馈List [List []]。
因此 -
val header = CsvParser.parse(lines.next).flatten
val rowMapsIterator =
| for (line <- lines)
| yield (header zip CsvParser.parse(line).flatten).toMap
这给了我一个标题col到数据列映射的地图
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)