编写一个 MapReduce 程序来对 Hadoop.txt 中各个单词出现的次数进行统计
时间: 2024-03-17 08:41:41 浏览: 84
Hadoop- 单词计数(Word Count)的MapReduce实现.doc
好的,这个问题可以通过编写一个 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 中各个单词出现的次数进行统计,并将结果输出到指定的输出路径中。
阅读全文