Merge the intersection of two CSV files with Scala

后端 未结 2 840
悲哀的现实
悲哀的现实 2020-12-28 11:39

From input 1:

fruit, apple, cider  
animal, beef, burger

and input 2:

animal, beef, 5kg
fruit, apple, 2liter
fish, tuna,          


        
2条回答
  •  不知归路
    2020-12-28 12:02

    It's tough to infer a requirement from one example. May be something like this is would serve your needs:

    • Create a map from key to line for the second file f2 (so from "animal, beef" -> "5kg")
    • For each lines in the first file f1, get the key to look up in the map
    • Look up value, if found write output

    That translates to

    val f1 = Source fromFile "file1.csv" getLines
    val f2 = Source fromFile "file2.csv" getLines
    val map = f2.map(_.split(", *")).map(arr => arr.init.mkString(", ") -> arr.last}.toMap
    for {
      line <- f1
      key = line.split(", *").init.mkString(", ")
      value <- map.get(key)
    } {
      out.write(line + ", " + value + "\n")
    }
    

提交回复
热议问题