我试图用map reduce程序计算文件中每个字母出现的概率。
我使用下面的框架进行map reduce。1个Map器Map所有字符,例如('a',1)。一个组合器,用于计算每个字符的总出现次数。1个减速机来计算平均值。
但是,我无法计算减速器中的平均值。因此,我添加了一个虚拟字符,每当Map器Map一个新字符时,它将被写入一次。
这个伪字符表示字符总数,我不知道如何在reducer中访问相同的字符,并用所有其他值除以总数。
对于ex,以下是组合器的输出。
# 10
a 2
b 2
c 2
d 4
我试过用一个减速机,它没有输出。
我特别需要知道必须写在减速机中的逻辑。
public void reduce(Text key, Iterable<DoubleWritable> values, Context context)
throws IOException, InterruptedException {
int wordCount = 0;
double total = 1;
System.out.println("In Reducer now!");
double avg = 0;
total = values.iterator().next().get();
avg = values.get() / total;
context.write(key, new DoubleWritable(avg));
}
上面的代码不会在输出上写入任何内容。
制图器
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String s = value.toString();
char[] arrayofChar = s.toCharArray();
for (char ch : arrayofChar) {
System.out.print(ch);
if (Character.isLetter(ch)) {
context.write(new Text(String.valueOf(ch)), new DoubleWritable(1));
context.write(new Text("#"), new DoubleWritable(1));
}
}
}
合路器
public void reduce(Text key, Iterable<DoubleWritable> values, Context context)
throws IOException, InterruptedException {
double total = 0;
System.out.println("In Combiner now!");
for (DoubleWritable value : values) {
total += value.get();
}
context.write(key, new DoubleWritable(total));
}
1条答案
按热度按时间11dmarpk1#
为了解决这个问题,我分别写了:
输出: