我有一个包含一些单词的列表,我需要从文本行中提取匹配的单词,我发现this,但它只能提取一个单词
密钥文件内容
这是一个关键字
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|
+--------------------+-----------------+
我想
返回所有匹配的关键字及其计数
,如果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)
答案 0 :(得分:0)
我设法通过使用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|
+--------------------+--------------------+-----+
答案 1 :(得分:0)
在 Spark 3.1+ 中regexp_extract_all
可用:
regexp_extract_all(str, regexp[, idx])
- 提取 str
中与 regexp
表达式匹配并对应于正则表达式组索引的所有字符串。
你原来的问题现在可以这样解决:
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|
#+--------------------+--------------------+-----+