栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 云计算 > 云平台

Spark Core篇(一)

云平台 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spark Core篇(一)

combineByKey 实现 reduceByKey

conf = SparkConf().setMaster("local").setAppName("WordCount")
sc = SparkContext(conf = conf)

def getSentences(nums):
    return LoremIpsum().get_sentences(nums)

def wordCountApp(data):
    data = sc.parallelize(data)
    words = data.filter( lambda line : len(line.strip()) != 0 ).flatMap(lambda line : line.strip().split(" ")).map(lambda word : word.replace("." , "").replace(",",""))
    # return words.map(lambda key : (key , 1)).reduceByKey(lambda a , b : a + b).sortByKey()
    return words.map(lambda word : (word , 1))

if __name__ == '__main__':
    nums = 1000
    data = list()
    data.append(getSentences(nums))
    result = wordCountApp(data)
    print(result.collect())

    # reduceByKey 实现
    resRDD = result.combineByKey(
        lambda word : 1 ,
        lambda acc , word : acc + word,
        lambda acc1 , acc2 : acc1 + acc2
    ).map(lambda x : (x[0] , x[1]))
    print(resRDD.collect())

combineByKey 实现 groupByKey

conf = SparkConf().setMaster("local").setAppName("WordCount")
sc = SparkContext(conf = conf)

def getSentences(nums):
    return LoremIpsum().get_sentences(nums)

def wordCountApp(data):
    data = sc.parallelize(data)
    words = data.filter( lambda line : len(line.strip()) != 0 ).flatMap(lambda line : line.strip().split(" ")).map(lambda word : word.replace("." , "").replace(",",""))
    # return words.map(lambda key : (key , 1)).reduceByKey(lambda a , b : a + b).sortByKey()
    return words.map(lambda word : (word , 1))

if __name__ == '__main__':
    nums = 1000
    data = list()
    data.append(getSentences(nums))
    result = wordCountApp(data)
    print(result.collect())


    # groupByKey实现
    resRDD = result.combineByKey(
        lambda cnt : [cnt],
        lambda acc , cnt : acc + [cnt], #lambda acc , cnt : acc.append(cnt)
        lambda acc1 , acc2 : acc1 + acc2
    )
    print(resRDD.collect())
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/896792.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号