如何对 RDD 进行字符串转换?

How to do a string transformation of an RDD?

我有一些文档,我必须从中提取每个单词,然后每个文档使用 Pyspark 聚合该单词出现的次数。我已经设法把它变成下面的格式

["of#['d2:3', 'd4:10', 'd1:6', 'd3:13', 'd5:6', 'd6:9', 'd7:5']",
 "is#['d2:3', 'd4:8', 'd1:5', 'd3:1', 'd5:4', 'd6:6', 'd7:1']",
 "country#['d2:3', 'd1:1', 'd5:2', 'd6:2']",
 "in#['d2:5', 'd4:13', 'd1:2', 'd3:2', 'd5:2', 'd6:3', 'd7:3']",
 "seventh#['d2:1']"]

我怎样才能将上面的 rdd 转换成类似的东西

of#d2:3, d4:10, d1:6, d3:13, d5:6, d6:9, d7:5, 
is#d2:3, d4:8, d1:5, d3:1, d5:4, d6:6, d7:1, 
country#d2:3, d1:1, d5:2, d6:2,
in#d2:5, d4:13, d1:2, d3:2, d5:2, d6:3, d7:3,
seventh#d2:1

我尝试了以下代码行,但出现错误。希望能就我出错的地方提供一些意见。

print(x.map(lambda x:str(x[0])+"#"+str(x[1])).take(5))

您似乎只想从这些字符串值中删除方括号和单引号。

你可以这样做:

import re

rdd1 = rdd.map(lambda x: re.sub(r"[\['\]]", "", x))

for i in rdd1.collect():
    print(i)
    
# of#d2:3, d4:10, d1:6, d3:13, d5:6, d6:9, d7:5
# is#d2:3, d4:8, d1:5, d3:1, d5:4, d6:6, d7:1
# country#d2:3, d1:1, d5:2, d6:2
# in#d2:5, d4:13, d1:2, d3:2, d5:2, d6:3, d7:3
# seventh#d2:1