你的输入字符串:
# spark is SparkSession object
s1 = 'The Adventure of the Blue Carbuncle The Adventure of the Blue Carbuncle The Adventure of the Blue Carbuncle; The Adventure of the Blue Carbuncle;'
# Split the string on ; and I parallelize it to make an rdd
rddData = spark.sparkContext.parallelize(rdd_Data.split(";"))
rddData.collect()
# ['The Adventure of the Blue Carbuncle The Adventure of the Blue Carbuncle The Adventure of the Blue Carbuncle', ' The Adventure of the Blue Carbuncle', '']
import itertools
final = (
rddData.filter(lambda x: x != "")
.map(lambda x: x.split(" "))
.flatMap(lambda x: itertools.combinations(x, 2))
.filter(lambda x: x[0] != "")
.map(lambda x: (x, 1))
.reduceByKey(lambda x, y: x + y).collect()
)
# [(('The', 'of'), 7), (('The', 'Blue'), 7), (('The', 'Carbuncle'), 7), (('Adventure', 'the'), 7), (('Adventure', 'Adventure'), 3), (('of', 'The'), 3), (('the', 'Adventure'), 3), (('the', 'the'), 3), (('Blue', 'The'), 3), (('Carbuncle', 'The'), 3), (('Adventure', 'The'), 3), (('of', 'the'), 7), (('of', 'Adventure'), 3), (('the', 'The'), 3), (('Blue', 'Adventure'), 3), (('Blue', 'the'), 3), (('Carbuncle', 'Adventure'), 3), (('Carbuncle', 'the'), 3), (('The', 'The'), 3), (('of', 'Blue'), 7), (('of', 'Carbuncle'), 7), (('of', 'of'), 3), (('Blue', 'Carbuncle'), 7), (('Blue', 'of'), 3), (('Blue', 'Blue'), 3), (('Carbuncle', 'of'), 3), (('Carbuncle', 'Blue'), 3), (('Carbuncle', 'Carbuncle'), 3), (('The', 'Adventure'), 7), (('The', 'the'), 7), (('Adventure', 'of'), 7), (('Adventure', 'Blue'), 7), (('Adventure', 'Carbuncle'), 7), (('the', 'Blue'), 7), (('the', 'Carbuncle'), 7), (('the', 'of'), 3)]
- 从第一个拆分中删除所有空格
- 用空格分割 x ,它是一个空格分隔的字符串
- 使用
itertools.combinations 分别创建 2 个元素的组合(flatMap 用于将每个单词与行中的每个其他单词配对)
- 映射和减少就像您对字数所做的那样