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 **********#
相关推荐
伊布拉西莫6 分钟前
【流畅的Python】第20章:并发执行器 — 学习笔记
笔记·python·学习
IT策士12 分钟前
Redis 从入门到精通:Python 操作 Redis
redis·python·bootstrap
编码者卢布18 分钟前
【Azure AI Search】 searchMode=any 和 searchMode=all 有什么区别?
人工智能·python·flask
Samooyou25 分钟前
大模型微调(Fine Tuning)
人工智能·python·ai·语言模型
qq_85730581927 分钟前
python语法
开发语言·python·算法
AI行业学习40 分钟前
CC-Switch v3.16.1 官方下载 | 安装配置详细教程【2026.6.10】
java·开发语言·vue.js·python·mysql·eclipse·html
早起CaiCai1 小时前
【Pytorch 实践1】手写数字
人工智能·pytorch·python
吴梓穆1 小时前
Python 语法基础 函数
开发语言·python
Kobebryant-Manba1 小时前
学习文本处理
开发语言·python
m0_617493941 小时前
PaddleOCR报错:OneDnnContext does not have the input Filter 解决方案汇总
python