Spark/Python,reduceByKey()然后找到出现最频繁的前10个单词及其频率。

3
我已经建立了一个拥有Hadoop + Spark的虚拟机,并且正在从我的HDFS中读取一个文本文件 "words.txt" ,然后调用map(), flatmap(),reduceByKey()方法并尝试获取前10个最常见的单词及其出现次数。大部分代码我已经完成了,但只需要找到一种方法来查找前10个。我知道我需要简单地遍历元组中的值(key是实际单词的字符串,但值是它在words.txt文件中出现的次数的整数),并且具有计数器来计算前10个。 (K,V)值对是关键字来自words.txt, 值=聚合值为它在文件中出现的次数的整数。下面的屏幕截图是在调用reduceByKey()之后,您可以看到 'the' 出现了40次(在右侧的屏幕截图末尾)。
这是输出结果: enter image description here 这是我目前的代码:
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等操作时返回的是什么...
非常感谢您的帮助。
1个回答

3
您可以在reduce之后反转,这样您就可以使用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 x: (x[1], x[0])).sortByKey(False).take(1)非常感谢您的代码,让我找到了重复次数最高的单词。但是我做了一点小改动。 - Dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接