下面的代码是简单的字数计算。程序生成的文件如下
key-value:
hello 5
world 10
good 4
morning 10
nice 5
但我的目标是数数字数。结果应该是5,这是否意味着我需要数一数钥匙的数目?如果是的话,我如何计算钥匙的数量?
以下是功能代码:
Map器
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WordCountMapper 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 {
String remove_pinct = value.toString.replaceAll("[\\pP+~$`^=|<>~`$^+=|<>¥×]", " ");
StringTokenizer itr = new StringTokenizer(value.toString());
while(itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write (word,one);
}
}
}
减速机
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.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);
}
}
作业控制
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCountJobControl {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, " word count ");
job.setJarByClass(WordCountJobControl.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);
}
}
2条答案
按热度按时间yws3nbqq1#
可以将减速器的数量限制为一个:
然后在减速机中计算
reduce
方法,并将此值写入cleanup
方法,类似这样:您还需要通过设置combiner class删除行:
hgb9j2n62#
制图器
减速机
作业控制