TypeCheckError:FlatMap和ParDo必须返回一个可迭代的

时间:2017-05-29 03:17:44

标签: python python-2.7 google-cloud-platform google-cloud-dataflow apache-beam

我正在使用Apache beam 2.x&创建一个谷歌数据流管道。蟒

基本上我有一个文本文件,每个新行都包含一个英文句子。

我正在尝试为每个新行/句子调用Google NLP(Sentiments)API。

所以我有一个调用NLP API的函数:

class CalculateSentiments(beam.DoFn):
  def process(self, element):
    language_client = language.Client()
    pre_text = re.sub('<[^>]*>', '', element)
    text = re.sub(r'[^\w]', ' ', pre_text)
    document = language_client.document_from_text(text)
    sentiment = document.analyze_sentiment().sentiment
    return sentiment.score

我正在使用ParDo为每个句子调用此函数。我假设,以下ParDo将自动从文本文件中为每一行调用NLP情绪api (基本上我不必迭代文本文件中的每一行!?)

output = lines | beam.ParDo(CalculateSentiments())

output | WriteToText(known_args.output)

但是在执行数据流后我得到了这个错误:

  

TypeCheckError:FlatMap和ParDo必须返回一个可迭代的。而是返回。 [在跑步时   &#39; ParDo(CalculateSentiments)&#39;]回溯(最近一次呼叫最后):
  文件   &#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/runners/direct/executor.py" ;,   第297行,致电       evaluator.process_element(value)File&#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/runners/direct/transform_evaluator.py",   第366行,在process_element中       self.runner.process(element)File&#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/runners/common.py",   第267行,正在处理中       self.reraise_augmented(exn)File&#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/runners/common.py",   第263行,正在处理中       self._dofn_simple_invoker(element)File&#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/runners/common.py",   第198行,在_dofn_simple_invoker中       self._process_outputs(element,self.dofn_process(element.value))文件   &#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/typehints/typecheck.py" ;,   第60行,正在处理中       return self.wrapper(self.dofn.process,args,kwargs)File&#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/typehints/typecheck.py",   第84行,包装中       return self._check_type(result)File&#34; /Users/gsattanthan/.local/lib/python2.7/site-packages/apache_beam/typehints/typecheck.py",   第98行,在_check_type中       %type(输出))

我做错了什么?我使用Pardo的方式与Apache beam doco中显示的非常相似!

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

实际上,用方括号包装返回变量会修复它。

现在有道理,为什么错误说它需要可迭代!

  

返回[sentiment.score]