【问题标题】:Read CSV File to OrderedMap读取 CSV 文件到 OrderedMap
【发布时间】:2017-06-13 06:12:44
【问题描述】:

我正在阅读CSV 文件并将数据添加到Scala 中的Map

 val br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileName)), "UTF-8"))
 val inputFormat = CSVFormat.newFormat(delimiter.charAt(0)).withHeader().withQuote('"')                                
 import scala.collection.JavaConverters._
 import org.apache.commons.csv.{CSVFormat, CSVParser}

  val csvRecords = new CSVParser(br, inputFormat).getRecords.asScala
  val buffer = for (csvRecord <- csvRecords; if csvRecords != null && csvRecords.nonEmpty)
    yield csvRecord.toMap.asScala                              
    buffer.toList                                                  

但是由于Map 没有排序,我无法按顺序阅读这些列。有没有办法按顺序读取 csvRecords?
CSV 文件包含逗号分隔值以及标题。它应该以List[mutable.LinkedHashMap[String, String]] 格式生成输出,类似于[["fname", "A", "lname", "B"], ["fname", "C", "lname", "D"]]

上面的代码可以工作,但不能保持顺序。例如:如果 CSV 文件包含按 fname、lname 顺序排列的列,则输出映射的 lname 在前,fname 在后。

【问题讨论】:

  • 请用示例数据和预期输出更新问题
  • 我编辑了示例输出的问题。我希望它会很清楚。
  • 您输入的文件是否只包含 fname 、 lname 的数据?
  • 没有。它有 100 列。为简化起见,我只提到了 2 列。

标签: scala


【解决方案1】:

如果我正确理解您的问题,这里有一种方法可以按顺序创建LinkedHashMaps 列表:

// Assuming your CSV File has the following content:
fname,lname,grade
John,Doe,A
Ann,Cole,B
David,Jones,C
Mike,Duke,D
Jenn,Rivers,E

import collection.mutable.LinkedHashMap

// Get indexed header from CSV
val indexedHeader = io.Source.fromFile("/path/to/csvfile").
  getLines.take(1).next.
  split(",").
  zipWithIndex

indexedHeader: Array[(String, Int)] = Array((fname,0), (lname,1), (grade,2))

// Aggregate LinkedHashMap using foldLeft
val ListOfLHM = for ( csvRecord <- csvRecords ) yield    
  indexedHeader.foldLeft(LinkedHashMap[String, String]())(
    (acc, x) => acc += (x._1 -> csvRecord.get(x._2))
  )

ListOfLHM: scala.collection.mutable.Buffer[scala.collection.mutable.LinkedHashMap[String,String]] = ArrayBuffer(
  Map(fname -> John, lname -> Doe, grade -> A),
  Map(fname -> Ann, lname -> Cole, grade -> B),
  Map(fname -> David, lname -> Jones, grade -> C),
  Map(fname -> Mike, lname -> Duke, grade -> D),
  Map(fname -> Jenn, lname -> Rivers, grade -> E)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2018-10-24
    相关资源
    最近更新 更多