簡體   English   中英

每個文件計數的WordCount示例

[英]WordCount example with Count per file

我在獲取每個文件中單詞出現總數的詳細信息時遇到問題。 例如,我有四個文本文件(t1,t2,t3,t4)。 單詞w1在文件t2中是兩次,在t4中是一次,總共出現3次。 我想在輸出文件中寫入相同的信息。 我正在獲取每個文件中的單詞總數,但無法獲得如上所述的結果。

這是我的地圖課。

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
//line added
import org.apache.hadoop.mapreduce.lib.input.*;

public class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
private String pattern= "^[a-z][a-z0-9]*$";

public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
    String line = value.toString();
    StringTokenizer tokenizer = new StringTokenizer(line);
    //line added
    InputSplit inputSplit = context.getInputSplit();
    String fileName = ((FileSplit) inputSplit).getPath().getName();

    while (tokenizer.hasMoreTokens()) {
        word.set(tokenizer.nextToken());
        String stringWord = word.toString().toLowerCase();
        if ((stringWord).matches(pattern)){
            //context.write(new Text(stringWord), one);
            context.write(new Text(stringWord), one);
            context.write(new Text(fileName), one);
            //System.out.println(fileName);
            }
        }
    }
}

您可以通過將word用作key並將filename寫入value 現在,在減速器中,初始化每個文件的單獨計數器並更新它們。 為特定密鑰迭代所有值后,然后將每個文件的計數器寫入上下文。

在這里,您知道只有四個文件,因此可以對四個變量進行硬編碼。 請記住,您需要為在reducer中處理的每個新鍵重置變量。

如果文件數量更多,則可以使用Map。 在地圖中, filename名將是key並繼續更新value

在映射器的輸出中,我們可以將文本文件名設置為鍵,並將文件中的每一行設置為值。 該減速器為您提供文件名,單詞及其相應的計數。

public class Reduce extends Reducer<Text, Text, Text, Text> {
    HashMap<String, Integer>input = new HashMap<String, Integer>();

    public void reduce(Text key, Iterable<Text> values , Context context)
    throws IOException, InterruptedException {
        int sum = 0;
        for(Text val: values){
            String word = val.toString(); -- processing each row
            String[] wordarray = word.split(' '); -- assuming the delimiter is a space
            for(int i=0 ; i<wordarray.length; i++)
           {
            if(input.get(wordarray[i]) == null){
            input.put(wordarray[i],1);}
            else{
             int value =input.get(wordarray[i]) +1 ; 
             input.put(wordarray[i],value);
             }
           }     

       context.write(new Text(key), new Text(input.toString()));
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM