【发布时间】:2015-12-19 06:28:12
【问题描述】:
我有一个要在 Spark 中实现的 python 代码,但是我无法为在 Spark 1.1 版本中实现的 RDD 获得正确的逻辑。这段代码在 Python 中完美运行,但我想用这段代码在 Spark 中实现。
import lxml.etree
import csv
sc = SparkContext
data = sc.textFile("pain001.xml")
rdd = sc.parallelize(data)
# compile xpath selectors for ele ment text
selectors = ('GrpHdr/MsgId', 'GrpHdr/CreDtTm') # etc...
xpath = [lxml.etree.XPath('{}/text()'.format(s)) for s in selectors]
# open result csv file
with open('pain.csv', 'w') as paincsv:
writer = csv.writer(paincsv)
# read file with 1 'CstmrCdtTrfInitn' record per line
with open(rdd) as painxml:
# process each record
for index, line in enumerate(painxml):
if not line.strip(): # allow empty lines
continue
try:
# each line is an xml doc
pain001 = lxml.etree.fromstring(line)
# move to the customer elem
elem = pain001.find('CstmrCdtTrfInitn')
# select each value and write to csv
writer.writerow([xp(elem)[0].strip() for xp in xpath])
except Exception, e:
# give a hint where things go bad
sys.stderr.write("Error line {}, {}".format(index, str(e)))
raise
I am getting error as RDD not iteratable
- 我想将此代码实现为函数并在 Spark 中实现为独立程序
- 我希望使用 python 模块在 HDFS 和 Spark 中的本地模式中处理输入文件。
感谢对问题的回应。
【问题讨论】:
标签: python hadoop apache-spark pyspark