当前位置:   article > 正文

5.7 spark算子简单案例 - Python

spark算子简单案例 - python

第1关:WordCount - 词频统计

# -*- coding: UTF-8 -*-
from pyspark import SparkContext
 
if __name__ == "__main__":
 
    """
        需求:对本地文件系统URI为:/root/wordcount.txt 的内容进行词频统计
    """
    # ********** Begin **********#
 
    sc = SparkContext("local","pySpark")
    rdd = sc.textFile("/root/wordcount.txt")
    values = rdd.flatMap(lambda x:str(x).split(" ")).map(lambda x:(x,1)).reduceByKey(lambda x,y:x+y).sortBy(lambda x:tuple(x)[1],False)
    print(values.collect())
 
    # ********** End **********#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

第2关:Friend Recommendation - 好友推荐

# -*- coding: UTF-8 -*-
from pyspark import SparkContext
 
def word_couple(word1, word2):
    if hash(word1) > hash(word2):
        return word1 + '_' + word2
    return word2 + '_' + word1
 
def relations(items):
    result = []
    for i in range(1, len(items)):
        result.append((word_couple(items[0], items[i]), 0))
        for j in range(i+1, len(items)):
            result.append((word_couple(items[i], items[j]), 1))
    return result
 
def fun2(x):
    values = tuple(x[1])
    return ((x[0], 0) if min(values)==0 else (x[0], sum(values)))
 
if __name__ == "__main__":
    """
        需求:对本地文件系统URI为:/root/friend.txt 的数据统计间接好友的数量
    """
    # ********** Begin **********#
    sc = SparkContext("local", "friend recommendation")
    src = sc.textFile("/root/friend.txt").map(lambda x:x.strip().encode('utf-8').split(" "))
    rdd = src.flatMap(relations).reduceByKey(lambda x,y:0 if x==0 or y==0 else x+y).filter(lambda x:x[1]>0)
    print(rdd.collect())
 
    # ********** End **********#
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/731442
推荐阅读
相关标签
  

闽ICP备14008679号