头歌大数据——MapReduce 基础实战 答案 无解析

这篇具有很好参考价值的文章主要介绍了头歌大数据——MapReduce 基础实战 答案 无解析。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

第1关:成绩统计

编程要求

使用MapReduce计算班级每个学生的最好成绩,输入文件路径为/user/test/input,请将计算后的结果输出到/user/test/output/目录下。

代码:

需要先在命令行启动HDFS

#命令行
start-dfs.sh

再在代码文件中写入以下代码

#代码文件
import java.io.IOException;
import java.util.StringTokenizer;
 
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount {
    /********** Begin **********/
	//Mapper函数
    public static class TokenizerMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        private int maxValue = 0;
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString(),"\n");
            while (itr.hasMoreTokens()) {
                String[] str = itr.nextToken().split(" ");
                String name = str[0];
                one.set(Integer.parseInt(str[1]));
                word.set(name);
                context.write(word,one);
            }
            //context.write(word,one);
        }
    }
    public static class IntSumReducer 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 maxAge = 0;
            int age = 0;
            for (IntWritable intWritable : values) {
                maxAge = Math.max(maxAge, intWritable.get());
            }
            result.set(maxAge);
            context.write(key, result);
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = new Job(conf, "word count");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        String inputfile = "/user/test/input";
        String outputFile = "/user/test/output/";
        FileInputFormat.addInputPath(job, new Path(inputfile));
        FileOutputFormat.setOutputPath(job, new Path(outputFile));
        job.waitForCompletion(true);
    /********** End **********/
    }
}

第2关:文件内容合并去重

编程要求

接下来我们通过一个练习来巩固学习到的MapReduce知识吧。

对于两个输入文件,即文件file1和文件file2,请编写MapReduce程序,对两个文件进行合并,并剔除其中重复的内容,得到一个新的输出文件file3。 为了完成文件合并去重的任务,你编写的程序要能将含有重复内容的不同文件合并到一个没有重复的整合文件,规则如下:

  • 第一列按学号排列;
  • 学号相同,按x,y,z排列;
  • 输入文件路径为:/user/tmp/input/
  • 输出路径为:/user/tmp/output/

注意:输入文件后台已经帮你创建好了,不需要你再重复创建。

 代码:

需要先在命令行启动HDFS

#命令行
start-dfs.sh

再在代码文件中写入以下代码:文章来源地址https://www.toymoban.com/news/detail-480217.html

#代码文件
import java.io.IOException;

import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class Merge {

	/**
	 * @param args
	 * 对A,B两个文件进行合并,并剔除其中重复的内容,得到一个新的输出文件C
	 */
	//在这重载map函数,直接将输入中的value复制到输出数据的key上 注意在map方法中要抛出异常:throws IOException,InterruptedException
	public static class Map  extends Mapper<Object, Text, Text, Text>{
	
    /********** Begin **********/

        public void map(Object key, Text value, Context content) 
            throws IOException, InterruptedException {  
            Text text1 = new Text();
            Text text2 = new Text();
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                text1.set(itr.nextToken());
                text2.set(itr.nextToken());
                content.write(text1, text2);
            }
        }  
	/********** End **********/
	} 
		
	//在这重载reduce函数,直接将输入中的key复制到输出数据的key上  注意在reduce方法上要抛出异常:throws IOException,InterruptedException
	public static class  Reduce extends Reducer<Text, Text, Text, Text> {
    /********** Begin **********/
        
        public void reduce(Text key, Iterable<Text> values, Context context) 
            throws IOException, InterruptedException {
            Set<String> set = new TreeSet<String>();
            for(Text tex : values){
                set.add(tex.toString());
            }
            for(String tex : set){
                context.write(key, new Text(tex));
            }
        }  
    
	/********** End **********/

	}
	
	public static void main(String[] args) throws Exception{

		// TODO Auto-generated method stub
		Configuration conf = new Configuration();
		conf.set("fs.default.name","hdfs://localhost:9000");
		
		Job job = Job.getInstance(conf,"Merge and duplicate removal");
		job.setJarByClass(Merge.class);
		job.setMapperClass(Map.class);
		job.setCombinerClass(Reduce.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		String inputPath = "/user/tmp/input/";  //在这里设置输入路径
		String outputPath = "/user/tmp/output/";  //在这里设置输出路径

		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}

第3关:信息挖掘 - 挖掘父子关系

编程要求

你编写的程序要能挖掘父子辈关系,给出祖孙辈关系的表格。规则如下:

  • 孙子在前,祖父在后;
  • 输入文件路径:/user/reduce/input
  • 输出文件路径:/user/reduce/output

  代码:

需要先在命令行启动HDFS

#命令行
start-dfs.sh

再在代码文件中写入以下代码:

#代码文件
import java.io.IOException;
import java.util.*;

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.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class simple_data_mining {
	public static int time = 0;

	/**
	 * @param args
	 * 输入一个child-parent的表格
	 * 输出一个体现grandchild-grandparent关系的表格
	 */
	//Map将输入文件按照空格分割成child和parent,然后正序输出一次作为右表,反序输出一次作为左表,需要注意的是在输出的value中必须加上左右表区别标志
	public static class Map extends Mapper<Object, Text, Text, Text>{
		public void map(Object key, Text value, Context context) throws IOException,InterruptedException{
			/********** Begin **********/
		String line = value.toString();
             String[] childAndParent = line.split(" ");
             List<String> list = new ArrayList<>(2);
              for (String childOrParent : childAndParent) {
                 if (!"".equals(childOrParent)) {
                     list.add(childOrParent);
                  } 
              } 
              if (!"child".equals(list.get(0))) {
                  String childName = list.get(0);
                  String parentName = list.get(1);
                  String relationType = "1";
                  context.write(new Text(parentName), new Text(relationType + "+"
                        + childName + "+" + parentName));
                  relationType = "2";
                  context.write(new Text(childName), new Text(relationType + "+"
                        + childName + "+" + parentName));
              }
			/********** End **********/
		}
	}

	public static class Reduce extends Reducer<Text, Text, Text, Text>{
		public void reduce(Text key, Iterable<Text> values,Context context) throws IOException,InterruptedException{
				/********** Begin **********/

			    //输出表头
          if (time == 0) {
                context.write(new Text("grand_child"), new Text("grand_parent"));
                time++;
            }

				//获取value-list中value的child
List<String> grandChild = new ArrayList<>();

				//获取value-list中value的parent
 List<String> grandParent = new ArrayList<>();

				//左表,取出child放入grand_child
 for (Text text : values) {
                String s = text.toString();
                String[] relation = s.split("\\+");
                String relationType = relation[0];
                String childName = relation[1];
                String parentName = relation[2];
                if ("1".equals(relationType)) {
                    grandChild.add(childName);
                } else {
                    grandParent.add(parentName);
                }
            }

				//右表,取出parent放入grand_parent
 int grandParentNum = grandParent.size();
               int grandChildNum = grandChild.size();
               if (grandParentNum != 0 && grandChildNum != 0) {
                for (int m = 0; m < grandChildNum; m++) {
                    for (int n = 0; n < grandParentNum; n++) {
                        //输出结果
                    context.write(new Text(grandChild.get(m)), new Text(
                                grandParent.get(n)));
                    }
                }
            }
				/********** End **********/
		}
	}
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf,"Single table join");
		job.setJarByClass(simple_data_mining.class);
		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		String inputPath = "/user/reduce/input";   //设置输入路径
		String outputPath = "/user/reduce/output";   //设置输出路径
		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));
		System.exit(job.waitForCompletion(true) ? 0 : 1);

	}
}

到了这里,关于头歌大数据——MapReduce 基础实战 答案 无解析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 头歌大数据——HBase 伪分布式环境搭建

    第1关:HBASE伪分布式环境搭建 编程要求 好了,到你啦,你需要先按照上次实训——HBase单节点安装的方式将 HBase 安装在 /app 目录下,然后根据本关知识配置好伪分布式的 HBase ,最后点击测评即可通关。 测试说明 程序会检测你的 HBase 服务和 Hadoop 服务是否启动,以及伪分布

    2024年02月08日
    浏览(47)
  • 头歌大数据作业二:搭建Hadoop环境及HDFS

    课外作业二:搭建Hadoop环境及HDFS 作业详情 内容 阿里云-云起实验室-《搭建Hadoop环境》-Hadoop-2.10.1伪分布式: 1.截图本实验ECS的公网IP地址,并添加彩色框标注,如下图所示: 2.步骤6.启动Hadoop成功之后,截图并添加彩色框标注,如下图所示 3.hdfs 根目录创建文件夹(文件夹命

    2024年02月08日
    浏览(37)
  • 头歌答案--爬虫实战

    目录 urllib 爬虫  第1关:urllib基础 任务描述 第2关:urllib进阶  任务描述 requests 爬虫 第1关:requests 基础 任务描述 第2关:requests 进阶 任务描述 网页数据解析 第1关:XPath解析网页  任务描述 第2关:BeautifulSoup解析网页  任务描述 JSON数据解析 第1关:JSON解析  任务描述 爬虫

    2024年02月04日
    浏览(30)
  • 头歌答案Python——JSON基础

    目录 ​编辑 Python——JSON基础 第1关:JSON篇:JSON基础知识 任务描述 第2关:JSON篇:使用json库  任务描述 Python——XPath基础 第1关:XPath 路径表达式 任务描述 第2关:XPath 轴定位  任务描述 第3关:XPath 解析  任务描述 Python:什么是爬虫 第1关:什么是爬虫 任务描述 第2关:

    2024年01月17日
    浏览(32)
  • 【头歌】——数据分析与实践-python-网络爬虫-Scrapy爬虫基础-网页数据解析-requests 爬虫-JSON基础

    第1关 爬取网页的表格信息 第2关 爬取表格中指定单元格的信息 第3关 将单元格的信息保存到列表并排序 第4关 爬取div标签的信息 第5关 爬取单页多个div标签的信息 第6关 爬取多个网页的多个div标签的信息 第1关 Scarpy安装与项目创建 第2关 Scrapy核心原理 第1关 XPath解析网页 第

    2024年01月22日
    浏览(42)
  • 头歌JAVA数据结构答案

    一、Java数据结构-循环链表的设计与实现 第1关 单循环链表的实现—链表的添加、遍历 第2关 单循环链表的实现—链表的删除 第3关 双向循环链表的实现—链表的插入 第4关:双向循环链表的实现—链表的删除 二、Java数据结构-线性表的设计与实现 第1关:顺序表的实现之增删

    2024年02月08日
    浏览(31)
  • 大数据处理技术-头歌平台-答案

    这里是大数据处理技术的实训作业 ,学校使用的是“头歌”平台。(我已经不想吐槽了) 开始的几章很简单,所以没有写 其中有几章题目,仅仅需要ctrl+c ctrl+v即可,只是操作步骤麻烦一下,所以也没有写。 第一关:单机版安装 替换原有的configuration标签 第三关 第一关:伪

    2023年04月26日
    浏览(35)
  • 头歌MySQL数据库 - 初识MySQL 答案

    第1关:创建数据库 在右侧命令行中连接 MySQL ,并创建一个名为 MyDb 的数据库。 连接数据库的用户名为: root ,密码为: 123123 。 第2关:创建表 在右侧命令行中操作,创建数据库 TestDb ,在 TestDb 下创建表 t_emp ,表结构如下: 字段名称 数据类型 备注 id INT 员工编号 name VA

    2023年04月21日
    浏览(75)
  • 头歌MySQL数据库实训答案 有目录

    头歌MySQL数据库答案 特别感谢黄副班、小青提供代码,有问题联系公众号【学思则安】留言更正 其他作业链接 数据库1-MySQL数据定义与操作实战 MySQL数据库 - 初识MySQL MySQL数据库 - 数据库和表的基本操作(一) MySQL数据库 - 数据库和表的基本操作(二) MySQL数据库 - 单表查询

    2024年04月28日
    浏览(71)
  • 头歌Python实训答案——Python的几种数据结构

    第1关:列表及操作 #coding = utf-8 #********* Begin *********# #第一步 请在列表fruits中找出不属于水果一类元素,赋值给变量 a fruit = [\\\"苹果\\\",\\\"梨子\\\",\\\"菠萝\\\",\\\"黄瓜\\\",\\\"香蕉\\\"] a =\\\"黄瓜\\\" #第二步 将变量 a 的值添加到列表vegetable 的末尾 vegetable = [\\\"土豆\\\",\\\"萝卜\\\",\\\"茄子\\\",\\\"白菜\\\"] vegetable.append(a) #第三

    2024年02月05日
    浏览(59)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包