如何通过 csv 文件并从中创建 2 元组的映射?

How to go through a csv file and create map of 2 tuple out of it?

我有一个简单的 csv 文件,如下所示

Country    city        min    max
Germany    Berlin      13     6
Germany    Munich      19     6
Germany    Hamburg     19     18
Spain      Madrid      10     9
Spain      Barcelona   10     9

我想读取这个文件并创建一个 Map,它的键是一个元组,值是一个元组:

myMap = Map((country,city) , (min,max))

然后我可以浏览这张地图并检查我是否有钥匙(Germany,Berlin)我可以拉出它的最小值和最大值....

如何使用 csv reader 执行此操作?我正在使用 tototoshi

我正在使用 Scala,但 java 解决方案也很棒。

你应该使用 scala split 来获取一个正则表达式的值,这个正则表达式在这种情况下是空格,然后你有一个向量,它的组件是行中的单词。因此,您必须做的唯一一件事就是遍历数组以进行打印或将元素添加到您的结构中,在这种情况下为 Map[Tuple2[String,String],Tuple2[String,String]] 结构。您可以使用语法糖来使用此元组,但使用此代码很容易看出您在做什么

源代码:

object TestCSV extends App {
    val bufferedSource = io.Source.fromFile("/Users/toni/learn/scala/test-Whosebug/src/main/scala/com/cuaqea/csv/file.csv")
    val cache = collection.mutable.Map[Tuple2[String,String], Tuple2[String,String]]()
  for (line <- bufferedSource.getLines) {
        val cols = line.split("\s+").map(_.trim)

      println(s"${cols(0)}|${cols(1)}|${cols(2)}|${cols(3)}")
      cache += (new Tuple2(cols(0),cols(1)) -> new Tuple2(cols(2), cols(3)))

  }
  println(cache.toString)
    bufferedSource.close
}

结果:

[info] Running TestCSV
Country|city|min|max
Germany|Berlin|13|6
Germany|Munich|19|6
Germany|Hamburg|19|18
Spain|Madrid|10|9
Spain|Barcelona|10|9

Map((Country,city) -> (min,max), (Spain,Madrid) -> (10,9), (Germany,Berlin) -> (13,6), (Germany,Hamburg) -> (19,18), (Germany,Munich) -> (19,6), (Spain,Barcelona) -> (10,9))
[success] Total time: 8 s, completed Feb 18, 2016 10:41:31 AM

如果您愿意使用不同的 CSV 库,使用 kantan.csv:

相当简单
import kantan.csv.ops._

// Turn your file into an iterator of (String, String, Int, Int)
file.asUnsafeCsvReader[(String, String, Int, Int)](',', true)

// Turn each entry into a (String, String) -> (Int, Int)
  .map(c => (c._1 -> c._2) -> (c._3 -> c._4))

// Fold on the iterator to turn it into the desired map.
  .foldLeft(Map.empty[(String, String), (Int, Int)])(_ + _)

请注意,我已将您的分隔符(任意数量的空格)替换为 ,,因为它使事情更简单。