【问题标题】:Find top 10 most frequent words excluding “the”, “am”, “is”, and “are” in Hadoop MapReduce?找出 Hadoop MapReduce 中除“the”、“am”、“is”和“are”之外的 10 个最常用词?
【发布时间】:2019-02-14 02:56:45
【问题描述】:

我正在处理 MapReduce 的 WordsCount 问题。我使用了刘易斯卡罗尔著名的《通过镜子》的 txt 文件。它的文件很大。我运行了我的 MapReduce 代码,它工作正常。现在我需要找出除“the”、“am”、“is”和“are”之外最常见的 10 个单词。我不知道如何处理这个问题。

这是我的代码

public class WordCount {

public static class TokenizerMapper
        extends Mapper<Object, Text, Text, IntWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
    ) throws IOException, InterruptedException {
        StringTokenizer itr = new StringTokenizer(value.toString().replaceAll("[^a-zA-Z0-9]", " ").trim().toLowerCase());
        while (itr.hasMoreTokens()) {
            word.set(itr.nextToken());
            context.write(word, one);
        }
    }
}

public static class IntSumReducer
        extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
    ) throws IOException, InterruptedException {
        int sum = 0;
        for (IntWritable val : values) {
            sum += val.get();
        }

        result.set(sum);
        context.write(key, new IntWritable(sum));

    }
}


public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
   /* job.setSortComparatorClass(Text.Comparator.class);*/
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}

【问题讨论】:

标签: java hadoop mapreduce


【解决方案1】:

我个人不会写代码,除非我看到你的尝试比 Wordcount 需要更多的努力

您需要第二个 mapper 和 reducer 来执行 Top N 操作。如果您使用的是高级语言,例如 Pig、Hive、Spark 等,它会这样做。

对于初学者,您至少可以过滤掉 itr.nextToken() 中的单词,以防止第一个映射器看到它们。

然后,在 reducer 中,您的输出将是未排序的,但您已经将所有单词的总和获取到某个输出目录,这是获取顶部单词的必要第一步。

该问题的解决方案需要您创建一个新的 Job 对象来读取 第一个输出目录,写入一个 new 输出目录,并为每一行文本在映射器中生成 null, line 作为输出(使用 NullWritable 和 Text)。

有了这个,在reducer中,所有的文本行都会被发送到一个reducer迭代器中,所以为了得到Top N项,你可以创建一个TreeMap&lt;Integer, String&gt;来按count排序(参考Sorting Descending order: Java Map )。插入元素时,较大的值将自动推到树的顶部。您可以选择通过跟踪树中的最小元素来优化这一点,并且只插入大于它的项目,和/或跟踪树的大小并且只插入大于第 N 个项目的项目(如果您可能有数百个项目,这会有所帮助几千字)。

在将所有元素添加到树的循环之后,取出所有字符串值的前 N ​​个及其计数(树已经为您排序),并将它们从 reducer 中写出来。这样,您应该最终得到前 N 个项目。

【讨论】:

猜你喜欢
  • 2014-05-24
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多