Hadoop MapReduce 获取每个单词的百分比

Hadoop MapReduce to get percentage of each word

我正在使用 Hadoop Mapreduce 来获取单词和单词计数信息。除了每个单词的计数,我还需要找到每个单词在文档中显示的百分比。输出是这样的。 如果文档只包含三个单词"hello"、"world"和"kitty"。结果应该是这样的。

字数百分比

你好 40 0.4

世界 50 0.5

猫咪 10 0.1

我可以设置一个TOTAL_KEY来统计所有的单词,问题是当每个单词统计return的时候,结果会同时return。将每个单词输出到hdfs时,无法计算当时的百分比。

您可以在 Mapper 中设置一个计数器。

  1. 当您从映射器发出单词时,增加一个全局计数器来计算单词总数。
  2. 获取减速器中的计数器以获取发出的总字数。
  3. 使用一般方法计算百分比。
job.setJarByClass(WinnerCount.class);
    job.setMapperClass(WinnerCountMapper.class);
    //job.setCombinerClass(WinnerCountCombiner.class);
    job.setCombinerClass(WinnerCountCombiner.class);
    job.setReducerClass(WinnerCountReducer.class);
    job.setInputFormatClass(ChessInputFormat.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(inputPath));
    FileOutputFormat.setOutputPath(job, temp);


    job.waitForCompletion(true);

    Counters counters = job.getCounters();
    Counter total = counters.findCounter(WinnerCountMapper.MAP_COUNTER.TOTAL_TUPLE);
    //System.out.println(total.getDisplayName()+":"+total.getValue());

    /*if (hdfs.exists(output))
        hdfs.delete(output, true);*/

    Configuration conf2 = new Configuration();
    conf2.set("total", total.getValue()+"");
    Job job2 = Job.getInstance(conf2,"aggregation");

    job2.setJarByClass(WinnerCount.class);
    job2.setMapperClass(AggregationMapper.class);
    job2.setReducerClass(AggregationReducer.class);
    job2.setOutputKeyClass(Text.class);
    job2.setOutputValueClass(Text.class);