在 Spark 中读取 csv 时防止分隔符冲突

Prevent delimiter collision while reading csv in Spark

我正在尝试使用 CSV 数据集创建 RDD。

问题是我有一个列 location,它的结构类似于 (11112,222222),但我不使用它。

因此,当我将 map 函数与 split(",") 一起使用时,会产生两列。

这是我的代码:

     val header = collisionsRDD.first 

     case class Collision (date:String,time:String,borogh:String,zip:String,
      onStreet:String,crossStreet:String,                                  
      offStreet:String,numPersInjured:Int,
      numPersKilled:Int,numPedesInjured:Int,numPedesKilled:Int,
      numCyclInjured:Int,numCycleKilled:Int,numMotoInjured:Int)   


     val collisionsPlat = collisionsRDD.filter(h => h != header).
                map(x => x.split(",").map(x => x.replace("\"","")))

     val collisionsCase = collisionsPlat.map(x => Collision(x(0),
                                x(1), x(2), x(3),                  
                                x(8), x(9), x(10),
                                x(11).toInt,x(12).toInt,
                                x(13).toInt,x(14).toInt,
                                x(15).toInt,x(16).toInt,
                                x(17).toInt))
     collisionsCase.take(5)                                                  

如何捕捉此字段中的 , 而不将其视为 CSV 分隔符?

使用 spark-csv 读取文件,因为它启用了 quote 选项

对于 Spark 1.6:

sqlContext.read.format("com.databticks.spark.csv").load(file)

或对于 Spark 2:

spark.read.csv(file)

来自文档:

quote: by default the quote character is ", but can be set to any character. Delimiters inside quotes are ignored

$ cat abc.csv
a,b,c
1,"2,3,4",5
5,"7,8,9",10

scala> case class ABC (a: String, b: String, c: String)

scala> spark.read.option("header", "true").csv("abc.csv").as[ABC].show
+---+-----+---+
|  a|    b|  c|
+---+-----+---+
|  1|2,3,4|  5|
|  5|7,8,9| 10|
+---+-----+---+