利用MapReduce进行数据清洗

使用MapReduce,去除num.txt中以2开头的数字,将结果保存为num2.txt

package MR_9_12;

import java.io.IOException;



import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;



public class shuziMR {
    
    
	//使用MR的处理方式,去除num.txt中以2开头的数字,将结果保存为num2.txt
	public static class MyMapper extends Mapper<LongWritable, Text, Text , NullWritable> {
    
    
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context)
				throws IOException, InterruptedException {
    
    
			String line = value.toString();
			String[] words = line.split(",");
			for (String word : words) {
    
    
				if(!word.startsWith("2"))
					context.write(new Text(word), NullWritable.get());
			}
		}
	}
	
	
	public static class MyReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
    
    
		@Override
		protected void reduce(Text arg0, Iterable<NullWritable> arg1,
				Reducer<Text, NullWritable, Text, NullWritable>.Context arg2) throws IOException, InterruptedException {
    
    
			// TODO Auto-generated method stub
			// super.reduce(arg0, arg1, arg2);
			for (NullWritable nullWritable : arg1) {
    
    
				arg2.write(arg0, nullWritable);
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
    
    
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		job.setJarByClass(shuziMR.class);
		
		job.setMapperClass(MyMapper.class);
		job.setReducerClass(MyReducer.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(NullWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(NullWritable.class);
		
		FileInputFormat.setInputPaths(job, new Path("src/data/1.txt"));
		FileOutputFormat.setOutputPath(job, new Path("out/1ed.txt"));
		
		job.waitForCompletion(true);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_45750230/article/details/108572906