我正在尝试使用 PySpark 从列中提取正则表达式模式。我有一个包含正则表达式模式的数据框,然后是一个包含我想要匹配的字符串的表。
columns = ['id', 'text']
vals = [
(1, 'here is a Match1'),
(2, 'Do not match'),
(3, 'Match2 is another example'),
(4, 'Do not match'),
(5, 'here is a Match1')
]
df_to_extract = sql.createDataFrame(vals, columns)
columns = ['id', 'Regex', 'Replacement']
vals = [
(1, 'Match1', 'Found1'),
(2, 'Match2', 'Found2'),
]
df_regex = sql.createDataFrame(vals, columns)
我想匹配“df_to_extract”的“文本”列中的“正则表达式”列。我想提取针对每个 id 的术语,结果表包含 id 和与“正则表达式”相对应的“替换”。例如:
+---+------------+
| id| replacement|
+---+------------+
| 1| Found1|
| 3| Found2|
| 5| Found1|
+---+------------+
谢谢!
最佳答案
一种方法是使用 pyspark.sql.functions.expr
,它允许您 use a column value as a parameter , 在您的加入条件中。
例如:
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('%', r.Regex, '%')
它将连接所有 text
列类似于 Regex
列的所有行,其中 %
用作通配符以捕获前后的任何内容.
关于python - 表之间的 PySpark 正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54308022/