2017-01-03 179 views
0

如何用Scala中的双引号替换单引号?我有一个包含“abc”(双引号)的记录的数据文件。我需要用单引号替换这些引号并将其转换为数据帧。按行文件Scala:用单引号替换双引号

val customSchema_1 =   
    StructType(Array(
    StructField("ID", StringType, true), 
    StructField("KEY", StringType, true), 
    StructField("CODE", StringType, true)) 

val df_1 = sqlContext.read 
    .format("com.databricks.spark.csv") 
    .option("delimiter", "¦") 
    .schema(customSchema_1) 
    .load("example") 
+1

哪列有双引号?你的火花版本是什么? – mrsrinivas

+0

我正在使用火花芯1.6.0。引号中的数据分散在一些数据在列中有引号,而其他数据不包含。 – SFatima

+0

这听起来像是一个可能更容易用bash脚本解决的问题,但您基本上需要编写一个正则表达式,它将在双引号内找到所有双引号(用于您的列字符串),并用单引号替换它们。 –

回答

0

读线,并应用下面的例子来他们每个人:

val text: String = """Here is a lot of text and "quotes" so you may think that everything is ok until you see something "special" or "weird" 
""" 

text.replaceAll("\"", "'") 

这会给你加上引号,而不是双引号的新字符串值。

+0

感谢您的建议!如果您使用数据框架,您如何实现这一点?数据框中是否有一个函数可以允许这样做? – SFatima

0

您可以创建一个简单的UDF用单引号

我更换双引号是一个简单的例子

import org.apache.spark.sql.functions.udf 

val removeDoubleQuotes = udf((x:String) => s.replace("\"","'")) 

//If df is the dataframe and use the udf to colName to replace " with ' 

df.withColumn("colName", removeDoubleQuotes($"colName")) 

希望这有助于!