【问题标题】:Spark/Python, reduceByKey() then find top 10 most frequent words and frequenciesSpark/Python,reduceByKey() 然后找到前 10 个最常见的单词和频率
【发布时间】:2020-04-02 01:29:38
【问题描述】:

我有一个带有 Hadoop + Spark 的 VirtualMachine 设置,我正在从我的 HDFS 读取文本文件“words.txt”,然后调用 map()、flatmap()、reduceByKey() 和 尝试获取前 10 个最常见的单词及其出现。我已经完成了大部分代码,然后正在聚合元组列表,但我只需要找到前 10 个的方法。我知道我需要简单地遍历元组中的值(键是实际的 str 单词,但该值是单词在 words.txt 文件中出现的次数的整数)并且只有一个计数器来计算顶部10. (K,V) 值对是 Key = word.txt 中的单词,Value = 整数聚合值,表示它在文件中出现的次数。下面这个截图是在reduceByKey()已经被调用之后,你可以看到'the'出现了40次(屏幕截图的结尾在右边)

这是输出:

到目前为止,这是我的代码:

from pyspark import SparkcConf, SparkContext

# Spark set-up
conf = SparkConf()
conf.setAppName("Word count App")
sc = SparkContext(conf=conf)

# read from text file words.txt on HDFS
rdd = sc.textFile("/user/spark/words.txt")

# flatMap() to output multiple elements for each input value, split on space and make each word lowercase
rdd = rdd.flatMap(lamda x: x.lower().split(' '))

# Map a tuple and append int 1 for each word in words.txt
rdd = rdd.map(lamda x: (x,1))

# Perform aggregation (sum) all the int values for each unique key)
rdd = rdd.reduceByKey(lamda x, y: x+y)

# This is where I need a function or lambda to sort by descending order so I can grab the top 10 outputs, then print them out below with for loop

# for item in out:
print(item[0], '\t:\t', str(item[1]))

我知道我通常只会创建一个名为“max”的变量,并且只有在列表或元组中找到最大值时才更新它,但让我感到困惑的是我正在处理 Spark 和 RDD,所以我得到了错误,因为我有点困惑 RDD 在执行 map、flatmap、reduceByKey 等操作时返回的内容......

非常感谢任何帮助

【问题讨论】:

    标签: python apache-spark count tuples


    【解决方案1】:

    你可以在reduce之后反转K,V,这样你就可以使用sortByKey函数了:

    rdd.map(lambda (k,v): (v,k)).sortByKey(False).take(10)
    

    对于 Python 3:(因为不再支持 lambda 表达式中的元组解包)

    rdd.map(lambda x: (x[1], x[0])).sortByKey(False).take(10)
    

     

    【讨论】:

    • myrdd.map(lambda k: (k[1],k)).sortByKey(False).take(1) myrdd.map(lambda x: (x[1], x[0 ])).sortByKey(False).take(1) 非常感谢。你的代码让我找到重复次数最多的单词。但这是我所做的微小改变。
    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 2015-12-09
    • 2023-03-14
    • 2013-11-29
    • 2012-10-10
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多