如何编写一个MapReduce程序统计每个单词出现次数

2 篇文章 0 订阅
1 篇文章 0 订阅

1.准备资料

1.导入相关依赖

     <dependencies>
        <!--hadoop相关依赖-->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.1.3</version>
        </dependency>

        <!--日志相关的依赖-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.30</version>
        </dependency>
    </dependencies>

2.导入maven包管理工具,后续能帮助我们打包管理各种资源

<build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

3.在resources资源目录下创建一个log4j2.xml的配置文件,用来 配置日志信息

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error" strict="true" name="XMLConfig">
    <Appenders>
        <!-- 类型名为Console,名称为必须属性 -->
        <Appender type="Console" name="STDOUT">
            <!-- 布局为PatternLayout的方式,
            输出样式为[INFO] [2018-01-22 17:34:01][org.test.Console]I'm here -->
            <Layout type="PatternLayout"
                    pattern="[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c{10}]%m%n" />
        </Appender>

    </Appenders>

    <Loggers>
        <!-- 可加性为false -->
        <Logger name="test" level="info" additivity="false">
            <AppenderRef ref="STDOUT" />
        </Logger>

        <!-- root loggerConfig设置 -->
        <Root level="info">
            <AppenderRef ref="STDOUT" />
        </Root>
    </Loggers>

</Configuration>

4.准备好一个待统计单词个数的文本文件,如下所示:

 

2.编写代码

MapReudce的代码主要分三段:分别是map、reduce和driver,注意导包等细节

map阶段代码如下:

/**
 * LongWritable, Text,Text, IntWritable
 * LongWritable : 是输入的文本
 * Text : 输入的一行内容
 * Text : 输出的一个单词
 * IntWritable : 输出的单词的个数
 */
public class WCMapper extends Mapper<LongWritable, Text,Text, IntWritable> {

    private Text outKey = new Text();
    private IntWritable outValue = new IntWritable(1);
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //1.将value转化为String类型的数据进行操作,并获取一行数据进行操作
        String line = value.toString();
        String[] words = line.split(" ");  //将一行中的每个单词使用" "分开

        //2.遍历一行数据
        for (String word : words) {
            //将获取的word作为输出的key
            outKey.set(word);
            outValue.set(1);
            //3.将获取的每一个key和value都输出,并将其写出
            context.write(outKey,outValue);
        }

    }
}

 这里要注意,单词使用符号进行分割,就要使用相应的符号进行切分。

reduce阶段代码如下:

/**
 * Text map阶段输入的key类型
 * IntWritable map阶段输入的value类型
 * Text reduce阶段输出的key类型
 * IntWritable reduce阶段输出的value类型
 */
public class WCReducer extends Reducer<Text, IntWritable,Text,IntWritable> {

    private IntWritable outValue  = new IntWritable();
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

        //统计相同key元素的个数
        int sum = 0;
        for (IntWritable value : values) {
            sum += value.get();
        }

        //为输出的value赋值
        outValue.set(sum);
        
        //将相同的key的value全部统计好才将key和value写出
        context.write(key,outValue);
    }
}

 编写main方法类:

public class WCDriver {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        //1.设置配置文件
        Configuration conf = new Configuration();
        //2.获取一个Job实例对象
        Job job = Job.getInstance();

        //3.为job设置一个Driver
        job.setJarByClass(WCDriver.class);

        //4.为job设置mapper和reducer
        job.setMapperClass(WCMapper.class);
        job.setReducerClass(WCReducer.class);

        //5.设置job的map阶段输出的key和value类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        //6.设置job的reduce阶段输出的key和value类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        //7.设置文件的输入路径和输出路径
        FileInputFormat.setInputPaths(job,new Path("D:/test/wcinput"));
        FileOutputFormat.setOutputPath(job,new Path("D:/test/tout"));

        //8.开始执行任务
        boolean result = job.waitForCompletion(true);

        System.exit(result?0:1); //0正常退出程序,1异常退出程序
    }
}

 需要注意两点,1.若是在本地运行job.setJarByClass(WCDriver.class);可以不用写,但如果在集群上运行,上面代码不写会发生错误。2.文件的输出路径必须不能存在,否则或报错。Output directory file:/D:/test/tout already exists,可以将tout目录删除,或输入一个路径不存在的目录。

3.运行项目

经过几秒钟的运行,可以看到在file:/D/test/tout目录下生成了如下四个文件,前两个是.crc校验文件,用来校验输出的内容是否被修改 

 用编辑器打开后两个文件中的一个,看wordcount统计结果

可能会奇怪,第一行的1是什么呢,这里是因为输入的时候不小心按了两个空格,导致两个空格之间的空内容也被统计了一次。对比一下之前输入的单词,发现统计结果正确。简单的测试MapReduce程序完成。

 

 

  • 4
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题可以通过编写一个 MapReduce 程序来解决。以下是一个简单的 MapReduce 程序来对 Hadoop.txt 各个单词出现次数进行统计的示例: 1. Map 阶段 在 Map 阶段,我们将输入文件 Hadoop.txt 的每一行分解成单词,并将每个单词映射到一个键值对,其键是单词本身,值为 1,表示该单词出现了一次。 ```java public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable ONE = new IntWritable(1); private Text word = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); context.write(word, ONE); } } } ``` 2. Reduce 阶段 在 Reduce 阶段,我们将相同单词的键值对合并,并将它们的值相加,以得到每个单词出现的总次数。 ```java public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(key, new IntWritable(sum)); } } ``` 3. 驱动程序 在驱动程序,我们指定输入输出路径,以及 Mapper 和 Reducer 类。 ```java public class WordCountDriver { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCountDriver.class); job.setMapperClass(WordCountMapper.class); job.setCombinerClass(WordCountReducer.class); job.setReducerClass(WordCountReducer.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); } } ``` 以上代码可以将 Hadoop.txt 各个单词出现次数进行统计,并将结果输出到指定的输出路径

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值