2011-05-31 32 views
0

我有一個簡單的用例。在我的輸入文件中,我只需要計算總字數的百分比分佈。例如word1出現10次,word2出現5次等等,總的單詞數量是100,那麼我只需要顯示%word1 = 10%,%word2 = 5%等。所以每當我遇到一個單詞時,在map()和reduce中的context.write(word,1)總結了單個計數。但要計算我們需要總字數的百分比。我也在計算這個。reduce()方法中鍵的輸入順序是什麼

因此,在獲取word1或word2中的鍵的縮減之前,我需要爲每個單詞獲得百分比計算的總字數鍵。但在減少我得到這個總的話鍵後一些其他鍵。因此我無法計算百分比。

我也嘗試使用context.getConfiguration()。setFloat(「total count」,count)來設置map的配置總數。但在減少我無法從配置中獲得此值。它只是返回null。

任何建議請添加。

謝謝你..

+0

您可以嘗試使用計數器,而不是在配置中設置值。對於映射器中的每個單詞,只需增加計數器,然後在減速器中獲取該值。 – ajduff574 2011-05-31 14:34:38

+0

順便說一下,鍵的輸入順序是根據默認比較器進行排序的。所以如果是文本,那麼就是字典順序。但是,每個鍵只能使用一個Reducer,所以如果您希望代碼與多個Reducer配合使用,則不能只輸出總字數作爲鍵。 – ajduff574 2011-05-31 14:39:47

回答

0

您需要首先消化您的文檔,像這樣:

class WordCounter { 
    Map<String, Integer> totals = new HashMap<String, Integer>(); 
    int wordCount; 

    void digest(String document) { 
     for (String word : document.split("\\w+")) { 
      wordCount++; 
      Integer count = totals.get(word); 
      if (count == null) 
       totals.put(word, 1); 
      else 
       totals.put(word, ++count); 
     } 
    } 
} 

然後你就可以在你的文檔做第二遍做你與資訊喜歡你已收集,可能在每個字上使用類似此方法的東西:

String decorateWithPercent(String word) { 
    return word + " (" + (totals.get(word)/wordCount) + "%)"; 
} 

或打印頻率,如:

void printFrequencies() { 
    for (Map.Entry<String, Integer> wordCount : totals.entrySet()) { 
     System.out.println(wordCount.getKey() + " " + wordCount.getValue()); 
    } 
} 
+0

感謝您的建議。我想要使​​用單遍執行map reduce中的邏輯,因爲我想掃描的文件是15GB。 – sriram 2011-05-31 09:03:40

相關問題