在 PySpark 中使用 regexp_extract 提取多个单词
Extract multiple words using regexp_extract in PySpark
我有一个包含一些单词的列表,我需要从文本行中提取匹配的单词,我找到了 ,但它只提取了一个单词。
密钥文件内容
这是关键字
part_description 文件内容
32015 这是关键字hello world
代码
import pyspark.sql.functions as F
keywords = sc.textFile('file:///home/description_search/keys') #1
part_description = sc.textFile('file:///description_search/part_description') #2
keywords = keywords.map(lambda x: x.split(' ')) #3
keywords = keywords.collect()[0] #4
df = part_description.map(lambda r: Row(r)).toDF(['line']) #5
df.withColumn('extracted_word', F.regexp_extract(df['line'],'|'.join(keywords), 0)).show() #6
输出
+--------------------+--------------+
| line|extracted_word|
+--------------------+--------------+
|32015 this is a...| this|
+--------------------+--------------+
预期输出
+--------------------+-----------------+
| line| extracted_word|
+--------------------+-----------------+
|32015 this is a...|this,is,a,keyword|
+--------------------+-----------------+
我要
return 所有匹配关键字及其计数
如果step #4
是最有效的方法
可重现的例子:
keywords = ['this','is','a','keyword']
l = [('32015 this is a keyword hello world' , ),
('keyword this' , ),
('32015 this is a keyword hello world 32015 this is a keyword hello world' , ),
('keyword keyword' , ),
('is a' , )]
columns = ['line']
df=spark.createDataFrame(l, columns)
我设法通过使用 UDF 来解决它,如下所示
def build_regex(keywords):
res = '('
for key in keywords:
res += '\b' + key + '\b|'
res = res[0:len(res) - 1] + ')'
return res
def get_matching_string(line, regex):
matches = re.findall(regex, line)
return matches if matches else None
udf_func = udf(lambda line, regex: get_matching_string(line, regex),
ArrayType(StringType()))
df = df.withColumn('matched', udf_func(df['line'], F.lit(build_regex(keywords)))).withColumn('count', F.size('matched'))
结果
+--------------------+--------------------+-----+
| line| matched|count|
+--------------------+--------------------+-----+
|32015 this is ...|[this, is, this, ...| 5|
|12832 Shb is a...| [is, a]| 2|
|35015 this is ...| [this, is]| 2|
+--------------------+--------------------+-----+
在 Spark 3.1+ regexp_extract_all
中可用:
regexp_extract_all(str, regexp[, idx])
- Extract all strings in the str
that match the regexp
expression and corresponding to the regex group index.
你原来的问题现在可以这样解决:
re_pattern = '(' + '|'.join([f'\\b{k}\\b' for k in keywords]) + ')'
df = df.withColumn('matched', F.expr(f"regexp_extract_all(line, '{re_pattern}', 1)"))
df = df.withColumn('count', F.size('matched'))
df.show()
#+--------------------+--------------------+-----+
#| line| matched|count|
#+--------------------+--------------------+-----+
#|32015 this is a k...|[this, is, a, key...| 4|
#| keyword this| [keyword, this]| 2|
#|32015 this is a k...|[this, is, a, key...| 8|
#| keyword keyword| [keyword, keyword]| 2|
#| is a| [is, a]| 2|
#+--------------------+--------------------+-----+
pyspark REGEXP_EXTRACT_ALL 带临时视图
创建临时视图:
df.select("user_id","line").createOrReplaceTempView("temp")
Select 从临时视图创建一个新的临时视图或数据集:
spark.sql("SELECT user_id,REGEXP_EXTRACT_ALL(line,'(#[a-zA-Z]+)',1) as MATCHED FROM temp").createOrReplaceTempView("temp2")
对于这个例子,我使用 REGEXP_EXTRACT_ALL 来提取主题标签
我有一个包含一些单词的列表,我需要从文本行中提取匹配的单词,我找到了
密钥文件内容
这是关键字
part_description 文件内容
32015 这是关键字hello world
代码
import pyspark.sql.functions as F
keywords = sc.textFile('file:///home/description_search/keys') #1
part_description = sc.textFile('file:///description_search/part_description') #2
keywords = keywords.map(lambda x: x.split(' ')) #3
keywords = keywords.collect()[0] #4
df = part_description.map(lambda r: Row(r)).toDF(['line']) #5
df.withColumn('extracted_word', F.regexp_extract(df['line'],'|'.join(keywords), 0)).show() #6
输出
+--------------------+--------------+
| line|extracted_word|
+--------------------+--------------+
|32015 this is a...| this|
+--------------------+--------------+
预期输出
+--------------------+-----------------+
| line| extracted_word|
+--------------------+-----------------+
|32015 this is a...|this,is,a,keyword|
+--------------------+-----------------+
我要
return 所有匹配关键字及其计数
如果
step #4
是最有效的方法
可重现的例子:
keywords = ['this','is','a','keyword']
l = [('32015 this is a keyword hello world' , ),
('keyword this' , ),
('32015 this is a keyword hello world 32015 this is a keyword hello world' , ),
('keyword keyword' , ),
('is a' , )]
columns = ['line']
df=spark.createDataFrame(l, columns)
我设法通过使用 UDF 来解决它,如下所示
def build_regex(keywords):
res = '('
for key in keywords:
res += '\b' + key + '\b|'
res = res[0:len(res) - 1] + ')'
return res
def get_matching_string(line, regex):
matches = re.findall(regex, line)
return matches if matches else None
udf_func = udf(lambda line, regex: get_matching_string(line, regex),
ArrayType(StringType()))
df = df.withColumn('matched', udf_func(df['line'], F.lit(build_regex(keywords)))).withColumn('count', F.size('matched'))
结果
+--------------------+--------------------+-----+
| line| matched|count|
+--------------------+--------------------+-----+
|32015 this is ...|[this, is, this, ...| 5|
|12832 Shb is a...| [is, a]| 2|
|35015 this is ...| [this, is]| 2|
+--------------------+--------------------+-----+
在 Spark 3.1+ regexp_extract_all
中可用:
regexp_extract_all(str, regexp[, idx])
- Extract all strings in thestr
that match theregexp
expression and corresponding to the regex group index.
你原来的问题现在可以这样解决:
re_pattern = '(' + '|'.join([f'\\b{k}\\b' for k in keywords]) + ')'
df = df.withColumn('matched', F.expr(f"regexp_extract_all(line, '{re_pattern}', 1)"))
df = df.withColumn('count', F.size('matched'))
df.show()
#+--------------------+--------------------+-----+
#| line| matched|count|
#+--------------------+--------------------+-----+
#|32015 this is a k...|[this, is, a, key...| 4|
#| keyword this| [keyword, this]| 2|
#|32015 this is a k...|[this, is, a, key...| 8|
#| keyword keyword| [keyword, keyword]| 2|
#| is a| [is, a]| 2|
#+--------------------+--------------------+-----+
pyspark REGEXP_EXTRACT_ALL 带临时视图
创建临时视图:
df.select("user_id","line").createOrReplaceTempView("temp")
Select 从临时视图创建一个新的临时视图或数据集:
spark.sql("SELECT user_id,REGEXP_EXTRACT_ALL(line,'(#[a-zA-Z]+)',1) as MATCHED FROM temp").createOrReplaceTempView("temp2")
对于这个例子,我使用 REGEXP_EXTRACT_ALL 来提取主题标签