使用 MapReduce 统计文本文件中每个单词的出现次数
以下是使用 MapReduce 编程统计每个单词出现次数的示例代码:
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
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());
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, result);
}
}
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.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);
}
}
要运行上述代码,你需要将其保存为 WordCount.java,并在 Hadoop 环境中进行编译和运行。假设你已经安装了 Hadoop 并配置了环境变量,可以按照以下步骤运行代码:
- 将文本文件复制到 Hadoop 的输入目录中(例如,将文本文件拷贝到
/input
目录下)。 - 使用以下命令将 Java 源代码编译为可执行的 JAR 文件:
$ hadoop com.sun.tools.javac.Main WordCount.java $ jar cf wc.jar WordCount*.class
- 运行 MapReduce 作业:
其中,$ hadoop jar wc.jar WordCount /input /output
/input
是输入目录,/output
是输出目录。 - 查看输出文件:
输出应该类似于示例的输出结果。$ hadoop fs -cat /output/part-r-00000
请注意,该示例假设你已经正确设置并配置了 Hadoop 环境,并且将文本文件复制到了正确的输入目录中。你可能需要根据你的实际环境进行适当的调整。

原文地址: http://www.cveoy.top/t/topic/J7H 著作权归作者所有。请勿转载和采集!