我有一个包含一些单词的列表,我需要从文本行中提取匹配的单词,我找到了这个,但它只提取一个单词。
密钥文件内容
这是一个关键字
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)