我在获取每个文件的单词出现总数的分割时遇到了问题。
例如,我有四个文本文件(t1、t2、t3、t4)。单词 w1 在文件 t2 中出现了两次,在 t4 中出现了一次,总共出现了 3 次。
我想在输出文件中写入相同的信息。
我得到了每个文件中的总字数,但无法得到我想要的结果。
这是我的 map 课。
import java.io.IOException;
import java.util.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
//line added
import org.apache.hadoop.mapreduce.lib.input.*;
public class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
private String pattern= "^[a-z][a-z0-9]*$";
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
//line added
InputSplit inputSplit = context.getInputSplit();
String fileName = ((FileSplit) inputSplit).getPath().getName();
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
String stringWord = word.toString().toLowerCase();
if ((stringWord).matches(pattern)){
//context.write(new Text(stringWord), one);
context.write(new Text(stringWord), one);
context.write(new Text(fileName), one);
//System.out.println(fileName);
}
}
}
}
最佳答案
你可以通过写 word
来实现。如key
和 filename
如value
.现在在你的 reducer 中为每个文件初始化单独的计数器并更新它们。一旦针对特定键迭代了所有值,然后将每个文件的计数器写入上下文。
在这里您知道您只有四个文件,因此您可以硬编码四个变量。请记住,您需要为在 reducer 中处理的每个新键重置变量。
如果文件数量更多,则可以使用 Map.在 map 上,filename
将是 key
并继续更新value
.
关于java - 每个文件计数的 WordCount 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32969870/