需要帮助尝试解析文件并在 Scala 中创建地图 [英] Need help trying to parse file and create map in scala

查看:40
本文介绍了需要帮助尝试解析文件并在 Scala 中创建地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难思考如何解析 csv 文件并使用 Scala 将其发布到网络服务.

I am having a hard time wrapping my head around how to parse a csv file and post it to a webservice using scala.

基本思想是我需要从 csv 文件创建帖子参数.标题是参数,后面的行是值,即.

The basic idea is I need to create post params from the csv file. There for the header would be the parameters and the following rows would be the values ie.

示例 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 来解析数据,但似乎不知道接下来要做什么:

I have the following scala to parse the data but can't seem to figure out what to do next:

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) {

          }
        }
      }

推荐答案

这个怎么样?

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)

要获得该 & 分隔格式,您应该这样做:

To get that &-separated format, you would instead do:

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

这篇关于需要帮助尝试解析文件并在 Scala 中创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆