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

2024-04-19 11:55:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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")

Tags: lambdatextimportreinputconfresultresults
1条回答
网友
1楼 · 发布于 2024-04-19 11:55:42

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

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

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

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

因此,我们不能在RDD上使用append,也不能在list上使用saveAsTextFilecollect是RDD上获取RDD到驱动程序内存的方法。

如注释中所述,用saveAsTextFile保存sortedwordsCount,或用python打开文件,并使用results写入文件

相关问题 更多 >