Hadoop 统计文件中某个单词出现的次数

本文介绍了一个使用Hadoop MapReduce框架统计文本文件中特定单词出现次数的应用案例。通过自定义Mapper和Reducer类实现对指定单词“is”的计数,并展示了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


如文件word.txt内容如下:

what is you name?

my name is zhang san。

要求统计word.txt中出现“is”的次数?

 

代码如下:

PerWordMapper

package com.hadoop.wordcount;

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 PerWordMapper extends Mapper<Object, Text, Text, IntWritable> {

	public Text keyText = new Text();
	public IntWritable intValue = new IntWritable(1);
	
	@Override
	protected void map(Object key, Text value,
			Context context)
			throws IOException, InterruptedException {
		String str = value.toString();
		StringTokenizer to = new StringTokenizer(str);
		while (to.hasMoreTokens()) {
			String t = to.nextToken();
			//此处为判断统计字符串的地方
			if(t.equals("is")){
				keyText = new Text(t);
				context.write(keyText, intValue);
			}
	       
	     }
	}
}


 

PerWordReducer

package com.hadoop.wordcount;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class PerWordReducer extends Reducer<Text, IntWritable, Text, IntWritable> {

	public IntWritable intValue = new IntWritable(0);
	@Override
	protected void reduce(Text key, Iterable<IntWritable> value,
			Context context)
			throws IOException, InterruptedException {
		int sum = 0;
		while(value.iterator().hasNext()){
			sum += value.iterator().next().get();
		}
		intValue.set(sum);
		context.write(key, intValue);
	}
	
}


PerWordCount

package com.hadoop.wordcount;

import java.io.IOException;

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;
import org.apache.hadoop.util.GenericOptionsParser;

import com.hadoop.mapreducer.MapperClass;
import com.hadoop.mapreducer.ReducerClass;
import com.hadoop.mapreducer.WordCount;

public class PerWordCount {
	public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
		Configuration conf = new Configuration();
	    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
	    System.out.println("otherArgs.length:"+otherArgs.length);
	    if (otherArgs.length != 2) {
	      System.err.println("Usage: wordcount <in> <out>");
	      System.exit(2);
	    }
	    Job job = new Job(conf, "word count");
	    job.setJarByClass(PerWordCount.class);
	    job.setMapperClass(PerWordMapper.class);
	    job.setCombinerClass(PerWordReducer.class);
	    job.setReducerClass(PerWordReducer.class);
	    job.setOutputKeyClass(Text.class);
	    job.setOutputValueClass(IntWritable.class);
	    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
	    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
	    System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}



 

### Hadoop环境下的词频统计实现 #### 使用MapReduce框架编写WordCount程序 Hadoop是一个开源的分布式计算框架,广泛应用于大数据处理和分析任务中[^1]。对于词频统计这一常见的文本分析操作,可以通过Hadoop MapReduce框架来高效完成。 具体来说,词频统计指的是计算一段文本中每个单词出现的次数。为了在Hadoop环境下实现此功能,可以采用经典的`WordCount`案例作为起点[^2]: - **Mapper阶段**:读取输入文件中的每一行,并将其分割成多个单词;之后针对每一个单词输出键值对形式的数据,其中键为单词本身,而值设为1表示该单词被发现了一次。 ```java public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken().toLowerCase()); // 转换为小写以忽略大小写的差异 context.write(word, one); // 输出<word, 1> } } } ``` - **Reducer阶段**:接收来自不同Mapper实例产生的相同关键词对应的数值列表,累加这些数值得到最终的结果——即某个特定词语在整个文档集合里总共出现了多少次。 ```java public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); // 对应于同一个key的所有value求和 } result.set(sum); context.write(key, result); // 输出<word, total_count> } } ``` 上述代码片段展示了如何利用Java语言构建一个基本版本的`WordCount`应用。当运行这个作业时,用户需先准备好待处理的数据集,并按照指引将它们上传至HDFS系统中[^3]。接着配置好Job参数提交给集群执行即可获得所需的统计报告。 #### 数据准备与验证 假设已经有一个名为`my.txt`的纯文本文件位于用户的主目录下,则可通过如下指令序列来进行后续的操作: ```bash # 创建远程路径/user/username/ hdfs dfs -mkdir -p /user/$USER # 将本地文件上传到指定位置 hdfs dfs -put ~/my.txt /user/$USER/ # 查看已成功传输的内容 hdfs dfs -cat /user/$USER/my.txt ``` 以上命令帮助确认源材料已被正确加载到了目标环境中,从而为下一步启动MapReduce任务奠定了基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值