spark算子简单案例 - Python

第1关:WordCount - 词频统计

python 复制代码
# -*- 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 **********#

第2关:Friend Recommendation - 好友推荐

python 复制代码
# -*- 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 **********#
相关推荐
m0_3776182333 分钟前
Golang怎么连接MySQL数据库_Golang MySQL连接教程【总结】
jvm·数据库·python
LN花开富贵1 小时前
【ROS】鱼香ROS2学习笔记一
linux·笔记·python·学习·嵌入式·ros·agv
weixin_586061461 小时前
C#怎么通过反射获取类属性_C#如何动态读取元数据【进阶】
jvm·数据库·python
Jurio.1 小时前
本机开发 + 多机执行的极简远端运行工具
linux·git·python·github·远程工作
skywalk81631 小时前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
overmind1 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
m0_678485452 小时前
CSS如何控制表格单元格边框合并_通过border-collapse实现
jvm·数据库·python
m0_748839492 小时前
如何用组合继承模式实现父类方法复用与子类属性独立
jvm·数据库·python
qq_334563552 小时前
PHP源码是否依赖特定芯片组_Intel与AMD平台差异【操作】
jvm·数据库·python
qq_206901393 小时前
如何使用C#调用Oracle存储过程_OracleCommand配置CommandType.StoredProcedure
jvm·数据库·python