2017-02-04 72 views
1

此python3程序嘗試使用map/reduce從文本文件生成單詞的頻率列表。我想知道如何在第二個減速器的產量表中對單詞計數進行排序,表示爲「count」,以便最後出現最大的計數值。目前,該成果的尾部看起來就像這樣:映射/減少計數的兩階段排序

"0002" "wouldn" 
"0002" "wrap" 
"0002" "x" 
"0002" "xxx" 
"0002" "young" 
"0002" "zone" 

對於情況下,我通過任何字的文本文件到python3程序是這樣的:

python MapReduceWordFreqCounter.py book.txt 

這裏是MapReduceWordFreqCounter.py代碼:

from mrjob.job import MRJob 
from mrjob.step import MRStep 
import re 

# ignore whitespace characters 
WORD_REGEXP = re.compile(r"[\w']+") 

class MapReduceWordFreqCounter(MRJob): 

    def steps(self): 
     return [ 
      MRStep(mapper=self.mapper_get_words, 
        reducer=self.reducer_count_words), 
      MRStep(mapper=self.mapper_make_counts_key, 
        reducer = self.reducer_output_words) 
     ] 

    def mapper_get_words(self, _, line): 
     words = WORD_REGEXP.findall(line) 
     for word in words: 
      yield word.lower(), 1 

    def reducer_count_words(self, word, values): 
     yield word, sum(values) 

    def mapper_make_counts_key(self, word, count): 
     yield str(count).rjust(4,'0'), word 

    def reducer_output_words(self, count, words): 
     for word in words: 
      yield count, word 

if __name__ == '__main__': 
    MapReduceWordFreqCounter.run()   

回答

1

你必須爲你的工作設置自定義分類比較器。

如果您在Java寫的,它看起來像

job.setSortComparatorClass(SortKeyComparator.class); 

,你就必須提供一個類,讓相反的順序

public class SortKeyComparator extends Text.Comparator { 

    @Override 
    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { 
     return (-1) * super.compare(b1, s1, l1, b2, s2, l2); 
    } 
} 

我猜蟒蛇Hadoop的API有一些simular做這個伎倆的方法。

0

對於MRJob Reduce步驟,沒有期望結果應該按鍵'count'排序。

此處,MRJob導入允許您在本地和AWS Elastic MapReduce集羣上運行代碼。 MRJob執行繁重的工作,因爲它使用Yarn API和Hadoop流進行映射和縮減作業之間的分佈式數據傳輸。

例如,在本地運行,則可以運行該MRJob爲: 蟒MapReduceWordFreqCounter.py -r EMR: 蟒MapReduceWordFreqCounter.py books.txt> counts.txt

要在單個EMR節點上運行books.txt> counts.txt

要在25個EMR節點上運行: 蟒MapReduceWordFreqCounter.py -r EMR --num-EC2-實例= 25 books.txt> counts.txt

要解決的分佈式EMR工作(替換您的工作ID): python -m mrjob.tools.emr.fetch_logs --find-failure j-1NXEMBAEQFDFT

這裏,在四個節點上運行時,縮減結果是按順序排列的,但在輸出文件的四個不同部分中。事實證明,強制減速器生成單個有序文件與僅在後運行作業步驟中排序結果相比,不具有性能優勢。因此,要解決這個具體問題的方法之一是使用Linux命令排序:

sort word_frequency_list.txt > sorted_word_frequency_list.txt 

產生這些「尾」的結果:

的「 「1191」

「0970」」「一」 「 1292" ‘的’ ‘1420’,‘你的’ ‘1561’,‘你’ ‘1828’,‘到’

更一般地,也有在Hadoop之上,非常適合這種處理的框架。對於這個問題,Pig可以在處理過的文件中讀取並計數。

豬可以通過Grunt shell或Pig腳本運行(使用區分大小寫的Pig拉丁語法)。豬腳本遵循下面的模板: 1)LOAD語句來讀取數據 2)A系列「轉型」語句來處理數據 3)轉儲/ STORE語句來保存結果

要使用豬訂購數:

reducer_count_output = LOAD 'word_frequency_list.txt' using PigStorage(' ') AS (word_count:chararray, word_name:chararray); 
counts_words_ordered = ORDER reducer_count_output BY word_count ASC; 
STORE counts_words_ordered INTO 'counts_words_ordered' USING PigStorage(':', '-schema');