Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

python - How to restore RDD of (key,value) pairs after it has been stored/read from a text file

I saved my RDD of (key, value) pairs to a text file using saveAsTextFile. After I read the text file back using sc.textFile("filename.txt") command, I ended up with strings, instead of (key, value) pairs. My keys used to be strings and values were lists of floats. Here's an example:

(u'ALM_0', [98.0, 110.0, 104.0, 6.0, 208.0, -262.0, 136.0, -204.67395833333333, 45.362440283766297, -196487.0, 1.0, 4.0, 2.5, 1.1180339887498949, 10.0, -46.0, 261.0, -3.6343749999999999])  

How do I easily convert this string to (key, value) pair? Is there Spark read command that will do it on read?

I am using Python interface to Spark.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ast.literal_eval should do the trick:

import ast

data1 = [(u'BAR_0', [1.0, 2.0, 3.0]), (u'FOO_1', [4.0, 5.0, 6.0])]
rdd = sc.parallelize(data1)
rdd.saveAsTextFile("foobar_text")

data2 = sc.textFile("foobar_text").map(ast.literal_eval).collect()
assert sorted(data1) == sorted(data2)

but generally speaking it is better to avoid situation like this in the first place and use for example a SequenceFile:

rdd.saveAsPickleFile("foobar_seq")
sc.pickleFile("foobar_seq")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...