写一个统计单词的mapreduce程序
时间: 2024-03-02 21:49:24 浏览: 75
统计单词程序
好的,以下是一个简单的MapReduce程序,用于统计输入文件中各个单词出现的次数:
Mapper 函数:
```
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private Text word = new Text();
private final static IntWritable ONE = new IntWritable(1);
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);
}
}
}
```
Reducer 函数:
```
public class WordCountReducer 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);
}
}
```
MapReduce 驱动程序:
```
public class WordCount {
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(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);
}
}
```
以上程序的作用是:读取输入文件,将每一行拆分为单词,然后输出每个单词以及它们出现的次数。其中,Mapper 函数读取每个单词,然后以 (单词,1) 的形式输出;Reducer 函数接收 Mapper 输出的键值对,对每个键进行求和,并输出最终结果;MapReduce 驱动程序则配置 Mapper、Reducer 函数和输入输出路径,启动 MapReduce 作业。
阅读全文