Spark 使用 Python:将 RDD 输出保存到文本文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34087137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:27:09  来源:igfitidea点击:

Spark using Python : save RDD output into text files

pythonapache-sparkpyspark

提问by RACHITA PATRO

I am trying the word count problem in spark using python. But I am facing the problem when I try to save the output RDD in a text file using .saveAsTextFile command. Here is my code. Please help me. I am stuck. Appreciate for your time.

我正在尝试使用 python 在 spark 中解决字数问题。但是当我尝试使用 .saveAsTextFile 命令将输出 RDD 保存在文本文件中时,我遇到了这个问题。这是我的代码。请帮我。我被困住了。感谢您的时间。

import re

from pyspark import SparkConf , SparkContext

def normalizewords(text):
    return re.compile(r'\W+',re.UNICODE).split(text.lower())

conf=SparkConf().setMaster("local[2]").setAppName("sorted result")
sc=SparkContext(conf=conf)

input=sc.textFile("file:///home/cloudera/PythonTask/sample.txt")

words=input.flatMap(normalizewords)

wordsCount=words.map(lambda x: (x,1)).reduceByKey(lambda x,y: x+y)

sortedwordsCount=wordsCount.map(lambda (x,y):(y,x)).sortByKey()

results=sortedwordsCount.collect()

for result in results:
    count=str(result[0])
    word=result[1].encode('ascii','ignore')

    if(word):
        print word +"\t\t"+ count

results.saveAsTextFile("/var/www/myoutput")

采纳答案by WoodChopper

since you collected results=sortedwordsCount.collect()so, its not RDD. It will be normal python list or tuple.

既然你收集了results=sortedwordsCount.collect(),它不是RDD。它将是普通的 python 列表或元组。

As you know listis python object/data structure and appendis method to add element.

如您所知list,python 对象/数据结构append是添加元素的方法。

>>> x = []
>>> x.append(5)
>>> x
[5]

Similarly RDDis sparks object/data structure and saveAsTextFileis method to write the file. Important thing is its distributed data structure.

同样 RDD是 sparks 对象/数据结构,saveAsTextFile也是写入文件的方法。重要的是它的分布式数据结构。

So, we cannot use appendon RDD or saveAsTextFileon list. collectis method on RDD to get to RDD to driver memory.

因此,我们不能append在 RDD 或saveAsTextFile列表上使用。collect是 RDD 上的方法,用于将 RDD 连接到驱动程序内存。

As mentioned in comments, save sortedwordsCountwith saveAsTextFile or open file in python and use resultsto write in a file

如评论中所述,sortedwordsCount使用 saveAsTextFile保存或在 python 中打开文件并用于results写入文件

回答by Derrick wang

Change results=sortedwordsCount.collect()to results=sortedwordsCount, because using .collect()results will be a list.

更改results=sortedwordsCount.collect()results=sortedwordsCount,因为使用.collect()结果将是一个列表。