在进行数据清洗时,使用spark 读取csv文件时,遭遇到数据列中存在 \n
的字符
原始数据:
names
“小红\n小明”
解析后数据:
index | names |
---|---|
1 | 小红 |
2 | 小明 |
我们想要的数据:
index | names |
---|---|
1 | “小红\n小明” |
在spark 读取时,会将\n
当成换行 ,将数据读取成两行数据,而我们不需要将解析引号内的数据,所以我们需要配置 csv读取格式 .option("quote", "\"")
,然而只配置 quote
还不够,我们还需要加入 .option("multiLine", "true")
df = sparkSession
.read
.format("csv")
.option("header", value = true)
.option("multiLine", "true")
.option("quote", "\"")
.option("sep", "\\t")
.load(input)
详细代码
val conf = new SparkConf().setAppName("data_clean")
conf.setMaster("local[*]")
conf.set("mapreduce.fileoutputcommitter.marksuccessfuljobs", "false")
conf.set("spark.sql.crossJoin.enabled", "true")
conf.set("spark.debug.maxToStringFields", "10000")
conf.set("spark.sql.debug.maxToStringFields", "10000")
conf.set("spark.sql.sources.commitProtocolClass", "org.apache.spark.sql.execution.datasources.SQLHadoopMapReduceCommitProtocol")
val sparkSession = SparkSession
.builder()
.config(conf)
.getOrCreate()
val df = sparkSession
.read
.format("csv")
.option("header", value = true)
.option("multiLine", "true")
.option("quote", "\"")
.option("sep", "\\t")
.load("C:\\Users\\Administrator\\Desktop\\data__e9de8e01692e47c1afe79c8e26282a62")