Final Project是利用Spark读取tweet文档,并做相应的分析。这个题目我前后共花费了两周的时间,在spark里艰难探索,最后发现其实并没有想象的那么难。所以还是打算把答案分享出来,供在此题中艰难探索的同志们参考一下。
# Import and create a new SQLContext
from pyspark.sql import SQLContext
sc=SparkContext.getOrCreate()
sqlContext = SQLContext(sc)
第一个坑,在Coursera给的ipynb文件里,是没有第二行的,所以直接运行会导致sc not found之类的提示。我查了半天论坛,试了好几种方法,最后发现其实只需要加上中间这行,就能够正常运行了,不需要重装pyspark什么的。
# Read the country CSV file into an RDD.
country_lines = sc.textFile('file:///home/cloudera/Downloads/big-data-3/final-project/country-list.csv')
# Convert each line into a pair of words
#country_lines.take(3)
words=country_lines.map(lambda line:line.split(","))
words.take(3)
这一步,就要将countryline转为(国家,国家缩写)的形式。我一开始做的时候,是参考了week2时候,莎士比亚文集的做法,以空格作为split, 并且用了flatmap,导致了结果大错特错。
这里稍微解释一下map。sc.textFile读取的文件格式,是将每一行视为一个单元块。而单元块里只会视为一个整体的字符串。例如country_list这个RDD,读取之后的形式应该是类似一个n1的数据组:
‘Afghanistan, AFG’
‘Albania, ALB’
…
而我们要做的,是要将每一行,拆分为两列。map函数的作用,就是对每一个单元块进行相同的操作, 有点类似pandas里的纵向apply函数。因此,如果我们map了一个split函数,就能将RDD结构转换为n2数据组:
‘Afghanistan‘, ‘ AFG’
‘Albania‘, ‘ALB’
…
就是我们想要的结果。
而flatmap函数,则是在对所有的单元格map了一个函数之后,再展成1*m的一维结构。
# Convert each pair of words into a tuple
country_tuples=words.map(lambda x :x)
在week2的题目中,这里map里的函数是lambda x:(x,1),意思是给每一个词都匹配一个数字1,是为了方便后续的统计。但此题中,由于我们在上面已经做了split的这个动作,因此在这一步仅仅是做一个赋值的动作,从words赋值到country_tuples里。
# Create the DataFrame, look at schema and contents
countryDF = sqlContext.createDataFrame(country_tuples, ["country", "code"])
countryDF.printSchema()
countryDF.take(3)
结果如下:
root
|-- country: string (nullable = true)
|-- code: string (nullable = true)
[Row(country='Afghanistan', code=' AFG'