python - 如何使用 pyspark 为非 pairwiseRDDs 正确 groupByKey

标签 python python-2.7 hadoop pyspark rdd

我是 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/

相关文章:

python - 如何让这个循环每次迭代增加 1.8?

hadoop - 仅将文件名检索到配置单元中的表中

python - 在 Python 3.4 中按索引访问 16.0 Pandas 数据框中的行时出现 keyerror

python - 第二次迭代文件不起作用

Python tkinter 弹跳球 - 能量趋于无穷大

python - 如何捕获多行字符串中某些字符和字符串之间的字符串? Python

python - 在大型二进制文件(2 GB 或更多)中使用正则表达式搜索字符串

python - 使用 raw_input 将 Python 的值添加到 Mysql

sql-server - Hadoop 2.8.1 Sqoop 1.4.6 从 SQL Server 数据导入问题?

unit-testing - 使用 MRUnit 进行 Hadoop 测试