我在spark数据框中有一个带有文本的列。
我想提取所有以特殊字符开头的单词,'@'
并regexp_extract
从该文本列的每一行中使用。如果文本包含多个以'@'
它开头的单词,则仅返回第一个。
我正在寻找提取与我的火花模式匹配的多个单词。
data_frame.withColumn("Names", regexp_extract($"text","(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9_]+)",1).show
输入样例: @always_nidhi @YouTube no i dnt understand bt i loved the music nd their dance awesome all the song of this mve is rocking
样本输出: @always_nidhi,@YouTube
您可以在spark中创建udf函数,如下所示:
import java.util.regex.Pattern
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.functions.lit
def regexp_extractAll = udf((job: String, exp: String, groupIdx: Int) => {
println("the column value is" + job.toString())
val pattern = Pattern.compile(exp.toString)
val m = pattern.matcher(job.toString)
var result = Seq[String]()
while (m.find) {
val temp =
result =result:+m.group(groupIdx)
}
result.mkString(",")
})
然后按如下所示调用udf:
data_frame.withColumn("Names", regexp_extractAll(new Column("text"), lit("@\\w+"), lit(0))).show()
在上方,您的输出如下:
+--------------------+
| Names|
+--------------------+
|@always_nidhi,@Yo...|
+--------------------+
根据您在问题中发布的输出,我使用了正则表达式。您可以对其进行修改以适合您的需求。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句