我正在使用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")
既然你收集了
results=sortedwordsCount.collect()
所以,它不是RDD。它将是普通的python列表或元组。如您所知,
list
是python对象/数据结构,append
是添加元素的方法。因此,我们不能在RDD上使用
append
,也不能在list上使用saveAsTextFile
。collect
是RDD上获取RDD到驱动程序内存的方法。如注释中所述,用saveAsTextFile保存
sortedwordsCount
,或用python打开文件,并使用results
写入文件相关问题 更多 >
编程相关推荐