我是 Python 新手。我也是 pysaprk 的新手。我正在尝试运行一个代码,它采用一个元组的元组,看起来像这样 (id , (span, mention))
来执行 .map(lambda (id, (span, text )): (id, text))
.
我正在使用的代码是:
m = text\
.map(lambda (id, (span, text)): (id, text))\
.mapValues(lambda v: ngrams(v, self.max_ngram))\'''error triggered here'''
.flatMap(lambda (target, tokens): (((target, t), 1) for t in tokens))\
原始数据的格式(id, source, span, text)
:
{'_id': u'en.wikipedia.org/wiki/Cerambycidae',
'source': 'en.wikipedia.org/wiki/Plinthocoelium_virens',
'span': (61, 73),
'text': u'"Plinthocoelium virens" is a species of beetle in the family Cerambycidae.'},
{'_id': u'en.wikipedia.org/wiki/Dru_Drury',
'source': 'en.wikipedia.org/wiki/Plinthocoelium_virens',
'span': (20, 29),
'text': u'It was described by Dru Drury in 1770.'}]
我收到这个错误:
for k, v in iterator:
TypeError: tuple indices must be integers, not str
我知道 groupByKey 在 pairwiseRDDs 上工作,所以我想知道如何正确执行 groupByKey 来解决这个问题?
我们将不胜感激任何帮助或指导。
我正在使用 python 2.7 和 pyspark 2.3.0。
提前谢谢你。
最佳答案
首先,您需要将数据映射到具有键和值的表单,然后是 groupByKey .
键和值形式始终是元组 (a, b),键为 a,值为 b。 a 和 b 本身可能是元组。
rdd = sc.parallelize([{'_id': u'en.wikipedia.org/wiki/Cerambycidae',
'source': 'en.wikipedia.org/wiki/Plinthocoelium_virens',
'span': (61, 73),
'text': u'"Plinthocoelium virens" is a species of beetle in the family Cerambycidae.'},
{'_id': u'en.wikipedia.org/wiki/Dru_Drury',
'source': 'en.wikipedia.org/wiki/Plinthocoelium_virens',
'span': (20, 29),
'text': u'It was described by Dru Drury in 1770.'},
{'_id': u'en.wikipedia.org/wiki/Dru_Drury',
'source': 'en.wikipedia.org/wiki/Plinthocoelium_virens2',
'span': (20, 29, 2),
'text': u'It was described by Dru Drury in 1770.2'}])
print rdd.map(lambda x: (x["_id"], (x["span"], x["text"]))).groupByKey()\
.map(lambda x: (x[0], list(x[1]))).collect()
[(u'en.wikipedia.org/wiki/Dru_Drury', [((20, 29), u'It was described by Dru Drury in 1770.'), ((20, 29, 2), u'It was described by Dru Drury in 1770.2')]), (u'en.wikipedia.org/wiki/Cerambycidae', [((61, 73), u'"Plinthocoelium virens" is a species of beetle in the family Cerambycidae.')])]
关于python - 如何使用 pyspark 为非 pairwiseRDDs 正确 groupByKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50426245/