我遇到問題以獲取每個文件的單詞出現總數的細目。例如, 我有四個文本文件(t1,t2,t3,t4)。字w1在文件t2中是兩次,並且在t4中一次,總共出現三次。 我想在輸出文件中寫入相同的信息。 我得到每個文件中的單詞總數,但不能像上面那樣得到我想要的結果。WordCount示例與每個文件的計數
這是我的地圖課。
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);
}
}
}
}
如果您想要爲每個文件分別生成結果,請將作業運行四次。如果你想要結合的結果然後提供所有的文件作爲輸入,你需要使用MultipleInput。 – YoungHobbit
結果的第一部分是可以的(這是所有文件中所有單詞的總髮生次數)。但我想用文件名來分解。 like,w1:3次出現(t2 x兩次,t1 x一次) – VD007