Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 从数据帧行中删除特殊字符_Regex_Scala_Apache Spark - Fatal编程技术网

Regex 从数据帧行中删除特殊字符

Regex 从数据帧行中删除特殊字符,regex,scala,apache-spark,Regex,Scala,Apache Spark,我有一个如下所示的数据集: ! Hello World. 1 " Hi there. 0 我想做的是,从每行的开头删除所有特殊字符,而不是从开头删除其余的特殊字符 为了读取数据选项卡,我使用以下代码: val data = sparkSession.read.format("com.databricks.spark.csv") .option("delimiter", "\t") .load("data.txt") val columns = Seq("text", "cl

我有一个如下所示的数据集:

! Hello World.  1
" Hi there. 0
我想做的是,从每行的开头删除所有特殊字符,而不是从开头删除其余的特殊字符

为了读取数据选项卡,我使用以下代码:

val data = sparkSession.read.format("com.databricks.spark.csv")
    .option("delimiter", "\t")
    .load("data.txt")

val columns = Seq("text", "class")
val df = data.toDF(columns: _*)
我知道我应该使用replaceAll,但我不太确定如何使用它

可能会有帮助

val str = " some string "
str.trim
或者修剪一些特定的字符

str.stripPrefix(",").stripSuffix(",").trim
或者从前面删除一些字符

val ignoreable = ", \t\r\n"
str.dropWhile(c => ignorable.indexOf(c) >= 0)
可以找到所有有用的带字符串的ops

您可以创建一个udf,并将其应用于数据帧的第一列,以删除前导特殊字符:

val df = Seq(("! Hello World.", 1), ("\" Hi there.", 0)).toDF("text", "class")

df.show
+--------------+-----+
|          text|class|
+--------------+-----+
|! Hello World.|    1|
|   " Hi there.|    0|
+--------------+-----+    


import org.apache.spark.sql.functions.udf
                                                           ^
// remove leading non-word characters from a string
def remove_leading: String => String = _.replaceAll("^\\W+", "")    
val udf_remove = udf(remove_leading)

df.withColumn("text", udf_remove($"text")).show
+------------+-----+
|        text|class|
+------------+-----+
|Hello World.|    1|
|   Hi there.|    0|
+------------+-----+