调用 MapReduce 对文件中的特殊字符和空格进行数据清洗,并对文件中各个单词出现的次数进行统计
时间: 2024-01-09 15:03:23 浏览: 85
可以使用MapReduce对文件进行数据清洗,并对文件中各个单词出现的次数进行统计,同时将特殊字符和空格进行清洗,具体步骤如下:
1. 编写Mapper类,将每个单词作为键,将值设置为1,输出键值对。在Mapper中使用正则表达式去除特殊字符和空格。
```java
public class WordCountMapper 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();
line = line.replaceAll("[^a-zA-Z0-9 ]", "").toLowerCase();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
```
2. 编写Reducer类,对相同键的值进行求和。
```java
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
```
3. 编写Main方法,设置Job的输入输出路径,并运行MapReduce程序。
```java
public class WordCount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(WordCountMapper.class);
job.setCombinerClass(WordCountReducer.class);
job.setReducerClass(WordCountReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
4. 将以上代码打包成可执行的jar文件,并将jar文件传入Hadoop集群,然后在命令行中运行以下命令:
```
hadoop jar WordCount.jar WordCount input output
```
其中,`WordCount`是程序名称,`input`是输入文件路径,`output`是输出文件路径。
运行成功后,输出文件中将包含每个单词出现的次数。同时,经过Mapper的处理,文件中的特殊字符和空格已经被清洗掉了。
阅读全文
相关推荐















