当前位置: 首页 > article >正文

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 **********#


第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 **********#


http://www.kler.cn/news/134061.html

相关文章:

  • 关于DBMS_STATS.GATHER_DATABASE_STATS_JOB_PROC的一些发现
  • 自学嵌入式,已经会用stm32做各种小东西了
  • 小米路由器AX1800降级后的SSH登录和关墙等命令
  • 【数据结构(二)】队列(2)
  • centos7安装mongodb
  • Cross-View Transformers for Real-Time Map-View Semantic Segmentation 论文阅读
  • 木子-前端-方法标签属性小记(普通jsp/html篇)2023~2024
  • Redis为什么是单线程的?Redis性能为什么很快?
  • psql 模式(SCHEMA)
  • ICCV 23丨3D-VisTA:用于 3D 视觉和文本对齐的预训练Transformer
  • python科研绘图:面积图
  • 一些RLHF的平替汇总
  • c语言常见的面试问题
  • Qt HTTP 摘要认证(海康球机摄像机ISAPI开发)
  • C语言——1.入门须知
  • TikTok与媒体素养:如何辨别虚假信息?
  • SpirngBoot + Vue 前后端分离开发工具代码
  • 阶乘算法优化
  • curl网络请求命令
  • milvus数据库索引管理
  • ClickHouse查看执行计划
  • CI/CD -gitlab
  • Notepad+正则表达式使用方法
  • ubuntu20编译ffmpeg3.3.6
  • Python实现视频字幕时间轴格式转换
  • 16. @PostConstruct注解和开关原理(验证码开关、IP开关)
  • 流量4----4
  • 【Java 进阶篇】JQuery 事件绑定:`on` 与 `off` 的奇妙舞曲
  • fully_connected与linear
  • C++学习 --vector