删除scala中的标点符号和无Ascii字符



我有一个数据集,在那里我正在阅读一些推文,我必须删除标点符号和非ascii字符,并将文本转换为小写字母。我如何在数据帧中实现这一点?有没有一种方法可以使用Spark Sql。

scala> data.show
+-----+--------------------+
|   id|               tweet|
+-----+--------------------+
|31963|#studiolife #aisl...|
|31964| @user #white #su...|
|31965|safe ways to heal...|
|31966|is the hp and the...|
|31967|  3rd #bihday to ...|
|31968|choose to be   :)...|
|31969|something inside ...|
|31970|#finished#tattoo#...|
|31971| @user @user @use...|

更通用的方法-将non-word字符替换为space以外的字符,如下所示-

val df = Seq("#studiolife #aisl", "@user #white #su", "oh! yeah #123 #su.").toDF("tweet")
df.withColumn("clean_tweet", regexp_replace($"tweet", "[\W&&[^\s+]]", ""))
.show(false)
/**
* +------------------+---------------+
* |tweet             |clean_tweet    |
* +------------------+---------------+
* |#studiolife #aisl |studiolife aisl|
* |@user #white #su  |user white su  |
* |oh! yeah #123 #su.|oh yeah 123 su |
* +------------------+---------------+
*/

对于DF列,用单个字符替换字符串列,请尝试以下操作:

import org.apache.spark.sql.functions._
regexp_replace(df.col,  "[\?,\.,\$]", ".")) 
... 
val res = df.withColumn("some_col_cleaned", regexp_replace(df("some_col"), "[\_,\*,\$,\#,\@]", "")) 
...

列的字符串类型为:

val res = df.withColumn("cleansed", regexp_replace(df("tweet"), "[\_,\*,\$,\#,\@,\&]", "")) 

工作良好

最新更新