[英]Spark/Python, reduceByKey() then find top 10 most frequent words and frequencies
我有一個帶有 Hadoop + Spark 的 VirtualMachine 設置,我正在從我的 HDFS 讀取文本文件“words.txt”,然后調用 map()、flatmap()、reduceByKey() 並嘗試獲取前 10 個最常用的單詞以及它們的發生。 我已經完成了大部分代碼,然后正在聚合元組列表,但我只需要一種方法來找到前 10 個。 我知道我需要簡單地遍歷元組中的值(鍵是實際的 str 單詞,但值是單詞在 words.txt 文件中出現的次數的整數)並且只需要一個計數器來計算頂部10. (K,V) 值對是 Key = word from words.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 等操作時返回的內容感到有些困惑……
非常感謝任何幫助
您可以在減少后反轉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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.