加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

表之间的PySpark正则表达式匹配

发布时间:2020-12-17 17:36:05 所属栏目:Python 来源:网络整理
导读:我正在尝试使用PySpark从列中提取正则表达式模式.我有一个包含正则表达式模式的数据框,然后有一个包含我要匹配的字符串的表. columns = ['id','text']vals = [ (1,'here is a Match1'),(2,'Do not match'),(3,'Match2 is another example'),(4,(5,'here is a

我正在尝试使用PySpark从列中提取正则表达式模式.我有一个包含正则表达式模式的数据框,然后有一个包含我要匹配的字符串的表.

columns = ['id','text']
vals = [
 (1,'here is a Match1'),(2,'Do not match'),(3,'Match2 is another example'),(4,(5,'here is a Match1')
]

df_to_extract = sql.createDataFrame(vals,columns)


columns = ['id','Regex','Replacement']
vals = [
(1,'Match1','Found1'),'Match2','Found2'),]

df_regex = sql.createDataFrame(vals,columns)

我想匹配“ df_to_extract”的“文本”列中的“正则表达式”列.我想针对每个ID提取术语,并在结果表中包含ID和与“ Regex”相对应的“替换”.例如:

+---+------------+
| id| replacement|
+---+------------+
|  1|      Found1|
|  3|      Found2|
|  5|      Found1|
+---+------------+

谢谢!

最佳答案
一种方法是在加入条件下使用pyspark.sql.functions.expr,它允许您将use a column value as a parameter设置为0.

例如:

from pyspark.sql.functions import expr
df_to_extract.alias("e")
    .join(
        df_regex.alias("r"),on=expr(r"e.text LIKE concat('%',r.Regex,'%')"),how="inner"
    )
    .select("e.id","r.Replacement")
    .show()
#+---+-----------+
#| id|Replacement|
#+---+-----------+
#|  1|     Found1|
#|  3|     Found2|
#|  5|     Found1|
#+---+-----------+

在这里,我使用了sql表达式:

e.text LIKE concat('%','%')

它将连接所有文本行类似于Regex列的行,其中%用作通配符以捕获之前和之后的所有内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读