读书笔记--MapReduce词频统计

本文深入解析MapReduce实现词频统计的全过程,包括Mapper和Reducer的代码实现,以及如何配置主程序。从输入文本文件到输出词频结果,详细阐述了MapReduce的工作原理。

       词频统计作为MapReduce入门的一个基础算法,相当与各种语言的“Hello World”程序。下面简单说一下MapReduce的算法实现。

       Mapper代码:

public class WordMapper extends Mapper<Object,Text,Text,IntWritable>{
    private IntWritable one = new IntWritable(1);
    private Text word = new Text();

    private String patter = "[^a-zA-Z0-9]";

    @Override
    protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
        //将非数字、英文的字符转换为空格
        StringTokenizer str = new StringTokenizer(value.toString().replaceAll(patter," ").toLowerCase());
        while(str.hasMoreTokens()){
            word.set(str.nextToken());
            context.write(word,one);
        }
    }
}

       一个文本文件被程序读取时,Mapper默认的LineRecordReader得到的value值是文本文件的一行,key值为初始偏移量。假如一个文本内容为:

       Hello World! Line one.

       Hello World! Line two.

       则第一次map获取到的value为:

       Hello World! Line one.

       Key为0。之后在map中通过循环,将单词一个个提取出来,通过context.write()方法输出为如<word,1>的键值对输出。此时输出的结果为:

       <hello,1>,<world,1>,<line,1>,<one,1>

       在节点的mapper处理完毕后,处理结果由Reducer处理(中间可以添加combiner、排序等此处暂时省略)。

       Reducer代码:

public class WordReducer extends Reducer<Text,IntWritable,Text,IntWritable>{

    private IntWritable result = new IntWritable();

    @Override
    protected 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,result);
    }
}

       Reducer将相同的key(并非一定相同,可以通过制定不同的算法使不同的值)分配到同一个reducer上。此时可以通过取出value的值进行相加,获得该单词的频率。最后通过context.write函数将结果输出为文本。

       Main方法:

public class WordCountTest {
    public static void main(String[] args) throws IOException {
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS", "hdfs://localhost:9000");
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        Job job=null;
        try{
            job=Job.getInstance(conf,"WordCount");
            job.setJarByClass(WordCountTest.class);
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);
            job.setMapperClass(WordMapper.class);
            job.setReducerClass(WordReducer.class);
            FileInputFormat.addInputPath(job,new Path(args[0]));
            FileOutputFormat.setOutputPath(job,new Path(args[1]));
            //job.setOutputFormatClass(SequenceFileOutputFormat.class);
            job.waitForCompletion(true);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

       注:Mapper和Reducer泛型声明的几个类型分别为:输入key类型、输入vlaue类型、输出key类型、输出value类型。

### 使用 MapReduce 实现词频统计 #### 1. 环境准备 为了实现基于Java的Hadoop MapReduce框架下的词频统计,需先准备好环境。这通常涉及安装配置好Hadoop集群以及设置好开发工具以便编写和提交MapReduce作业。 #### 2. 编写Mapper类 Mapper负责处理输入数据并将它们转换成键值对的形式。对于词频统计而言,每遇到一个单词就将其作为key输出一次,并附带value为1表示该单词出现了一次。 ```java public class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer itr = new StringTokenizer(line.toLowerCase()); while (itr.hasMoreTokens()) { word.set(itr.nextToken().replaceAll("[^a-z]", "")); if (!word.toString().isEmpty()) { // 排除非字母字符组成的字符串 context.write(word, one); } } } } ``` 这段代码展示了如何定义`TokenizerMapper`类来解析文本行并提取其中的各个词语[^1]。 #### 3. 编写Reducer类 Reducer接收来自多个mapper产生的相同key对应的values列表,对其进行聚合操作。在这个例子中就是累加所有相同的单词所关联的数量值得到最终的结果。 ```java public 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, result); } } ``` 此段落描述了`IntSumReducer`的功能及其具体实现方式。 #### 4. 配置Job 最后一步是在Driver程序里指定要使用的Mapper和Reducer类以及其他必要的参数如输入路径、输出路径等信息。 ```java Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: wordcount <in> <out>"); System.exit(2); } Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); ``` 上述代码片段说明了怎样构建一个完整的MapReduce任务,包括指定了输入输出文件夹的位置和其他重要属性。 通过以上步骤可以完成基本版的MapReduce词频统计应用。值得注意的是实际部署过程中还需要考虑更多细节比如错误处理机制、性能优化等方面的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值