HADOOP用eclipse统计以a开头和以b开头出现的单词个数
时间: 2024-03-22 16:42:01 浏览: 83
要使用Eclipse统计Hadoop中以a开头和以b开头出现的单词个数,需要进行以下步骤:
1. 创建Hadoop项目并导入Eclipse。
2. 在Eclipse中创建新的Java类,并编写MapReduce程序。
3. 在Map阶段,使用Java正则表达式匹配单词是否以a或b开头,将匹配到的单词作为key输出,value为1。
4. 在Reduce阶段,将相同key的value累加,得到每个单词出现的总次数。
5. 运行程序,将Hadoop输出的结果保存到本地文件中。
以下是代码示例:
```java
public class WordCount {
public static class Map 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()) {
String token = tokenizer.nextToken();
if(token.matches("(a|A|b|B)[a-zA-Z]*")) {
word.set(token);
context.write(word, one);
}
}
}
}
public static class Reduce 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));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "wordcount");
job.setJarByClass(WordCount.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}
```
在上述代码中,我们使用Java正则表达式 `(a|A|b|B)[a-zA-Z]*` 匹配以a或b开头的单词,其中 `[a-zA-Z]*` 表示单词的后缀可以由任意大小写字母组成。同时,我们在Map阶段将匹配到的单词作为key输出,value为1;在Reduce阶段将相同key的value累加,得到每个单词出现的总次数。
阅读全文
相关推荐
















