Scala:用单引号替换双引号

时间:2017-01-03 19:50:22

标签: scala dataframe spark-dataframe double-quotes single-quotes

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

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")

2 个答案:

答案 0 :(得分:1)

逐行阅读您的文件并将以下示例应用于每个文件:

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("\"", "'")

这将为您提供一个带引号而不是双引号的新String值。

答案 1 :(得分: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"))

希望这有帮助!

相关问题