我有一个文本文件。我需要在整个文档中找到重复单词对的可能计数。例如,我有下面的word文档。该文档有两行,每行之间用“;”分隔。文件:
My name is Sam My name is Sam My name is Sam;
My name is Sam;
我正在研究成对单词计数。预期结果是:
[(('my', 'my'), 3), (('name', 'is'), 7), (('is', 'name'), 3), (('sam', 'sam'), 3), (('my', 'name'), 7), (('name', 'sam'), 7), (('is', 'my'), 3), (('sam', 'is'), 3), (('my', 'sam'), 7), (('name', 'name'), 3), (('is', 'is'), 3), (('sam', 'my'), 3), (('my', 'is'), 7), (('name', 'my'), 3), (('is', 'sam'), 7), (('sam', 'name'), 3)]
如果我使用:
wordPairCount = rddData.map(lambda line: line.split()).flatMap(lambda x: [((x[i], x[i + 1]), 1) for i in range(0, len(x) - 1)]).reduceByKey(lambda a,b:a + b)
我得到连续单词的成对单词及其重复出现的次数。
如何将每个单词与该行中的每个其他单词配对,然后在所有行中搜索相同的单词对?
有人可以看看吗?谢谢
您的输入字符串:
# 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)]
itertools.combinations
创建两个元素的组合(flatMap
将行中的每个单词与其他单词配对)