在hadoop平台运行python代码的mapreduce的程序——排序

编程实现对输入文件排序⤴💮

一、实验目标

对3个文件中的数字排序,并输出。

file1.txt

33
37
12
40

file2.txt

4
16
39
5

file3.txt

1
45
25
2

最终实验效果:

二、编写mapper和reducer

mapper.py

文件内容如下:

#!/usr/bin/env python3
# encoding=utf-8

lines = []

import sys
for line in sys.stdin:
    line = line.strip()
    try:
        line = int(line)
    except ValueError:
        continue
    lines.append(line)

lines = sorted(lines)

for line in lines:
    print(line)

reducer.py

reducer.py文件如下:

#!/usr/bin/env python3
# encoding=utf-8

import sys

i = 1
for line in sys.stdin:
    line = line.strip()
    print("%d %s" % (i, line))
    i = i + 1

给mapper.py和reducer.py文件添加权限,需要输入一次密码。

sudo chmod 777 mapper.py
sudo chmod 777 reducer.py


三、创建三个输入文件

本文把file1.txt和file2.txt文件存放在/usr/local/hadoop目录下。 

file1.txt

33
37
12
40

file2.txt

4
16
39
5

file3.txt

1
45
25
2

把file1.txt、file2.txt和file3.txt上传到hdfs上。(在hdfs上先创建input文件夹)

./bin/hdfs dfs -put file1.txt input

./bin/hdfs dfs -put file2.txt input

./bin/hdfs dfs -put file3.txt input

四、运行程序

在本地测试mapper.py和reducer.py

cat file1.txt  file2.txt  file3.txt| python3 mapper.py |python3 reducer.py

在hdfs的文件中运行,最终结果写到hdfs中的output目录下。

 ./bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-3.3.5.jar -mapper mapper.py -reducer reducer.py -input input/* -output output

但是,我在hdfs上的文件运行结果不正确,翻车😭,是按照数字第一位排序,再按数字第二位排序,所以得到的就是 5排到12后面。和本地测试的结果不一样。

参考:实验5 MapReduce初级编程实践(Python实现)_对于两个输入文件,即文件a和文件b(需要分别按下文内容创建),编写mapreduce程序,对-CSDN博客https://blog.csdn.net/weixin_46584887/article/details/121317376

MapReduce是一种分布式计算模型,用于大规模数据集的并行处理。在C++中,虽然不是直接支持MapReduce的官方库,但我们可以通过Hadoop或Apache Spark等框架提供的API来实现类似的功能。WordCount是一个经典的MapReduce示例,它的目的是统计文本文件中每个单词出现的次数。 以下是简单的WordCount C++实现步骤: 1. **Mapper阶段**(Map函数): - 读取输入的一行文本(如"Hello World Hello") - 分割成单词数组,例如`{"Hello", "World", "Hello"}` - 对每个单词执行map操作,生成键值对`(word, 1)`,表示单词第一次出现。 ```cpp void map(std::string line, std::pair<std::string, int>& output) { std::istringstream iss(line); std::string word; while (iss >> word) { output.first = word; // 键 output.second = 1; // 值 emit(output); // 发送结果到中间件 } } ``` 2. **Reducer阶段**(Reduce函数): - 接收来自Mapper的所有相同键的值(在这里就是所有相同的单词),累加它们。 - 输出最终的键值对`(word, count)`。 ```cpp void reduce(const std::string& key, const std::vector<int>& values, std::pair<std::string, int>& output) { int sum = 0; for (int value : values) { sum += value; } output.first = key; output.second = sum; emit(output); // 发送到输出 } ``` 3. **使用框架提供的工具(如Hadoop Streaming)**将上述mapper和reducer程序连接起来,它会自动处理数据分发、排序、合并等工作。 4. **最后**,从reduce任务的输出中获取结果,即每个单词及其对应的出现次数。 请注意,这只是一个简化版本的解释,并未涉及所有细节,实际实现可能会涉及到序列化和反序列化、错误处理以及与Hadoop API的交互。此外,C++并不是首选的MapReduce语言,Python的PigLatin或Hadoop Streaming更适合这个场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值