Python结合Shell/Hadoop实现MapReduce

本文介绍了MapReduce的基本处理流程,包括catdata、map、sort和reduce等步骤,并提供了具体的mapper.py和reducer.py示例代码。此外还展示了如何在分布式环境中使用Hadoop Streaming来执行MapReduce任务。

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

基本流程为: 

cat data | map | sort | reduce

cat devProbe | ./mapper.py | sort| ./reducer.py

echo "foo foo quux labs foo bar quux" | ./mapper.py | sort -k1,1 | ./reducer.py

# -k, -key=POS1[,POS2]     键以pos1开始,以pos2结束

 

如不执行下述命令,可以再py文件前加上python调用

chmod +x mapper.py
chmod +x reducer.py

 

对于分布式环境下,可以使用以下命令:

hadoop jar /[YOUR_PATH]/hadoop/tools/lib/hadoop-streaming-2.6.0-cdh5.4.4.jar \
 -file mapper.py -mapper mapper.py \
 -file reducer.py -reducer reducer.py \
 -input [IN_FILE]    -output [OUT_DIR]

 

 

mapper.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-

__author__ = 'Manhua'

import sys
for line in sys.stdin:
    line = line.strip()
    item = line.split('`')
    print "%s\t%s" % (item[0]+'`'+item[1], 1)

 

reducer.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-

__author__ = 'Manhua'


import sys

current_word = None
current_count = 0
word = None

for line in sys.stdin:
    line = line.strip()
    word, count = line.split('\t', 1)
    try:
        count = int(count)
    except ValueError:  #count如果不是数字的话,直接忽略掉
        continue
    if current_word == word:
        current_count += count
    else:
        if current_word:
            print "%s\t%s" % (current_word, current_count)
        current_count = count
        current_word = word

if word == current_word:  #不要忘记最后的输出
    print "%s\t%s" % (current_word, current_count)

 

转载于:https://www.cnblogs.com/manhua/p/6593185.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值