用python写MapReduce函数 以WordCount为例,比较详细的

尽管Hadoop框架是用java写的,但是Hadoop程序不限于java,可以用python、C++、ruby等。本例子中直接用python写一个MapReduce实例,而不是用Jython把python代码转化成jar文件。

      例子的目的是统计输入文件的单词的词频。

输入:文本文件 输出:文本(每行包括单词和单词的词频,两者之间用'\t'隔开)

1. Python MapReduce 代码

      使用python写MapReduce的“诀窍”是利用Hadoop流的API,通过STDIN(标准输入)、STDOUT(标准输出)在Map函数和Reduce函数之间传递数据。

      我们唯一需要做的是利用Python的sys.stdin读取输入数据,并把我们的输出传送给sys.stdout。Hadoop流将会帮助我们处理别的任何事情。

1.1 Map阶段:mapper.py

在这里,我们假设把文件保存到hadoop-0.20.2/test/code/mapper.py

1. #!/usr/bin/env python
2. import sys
3. for line in sys.stdin:
4. line = line.strip()
5. <a href="http://www.it165.net/edu/ebg/" target="_blank" class="keylink">word</a>s = line.split()
6. for <a href="http://www.it165.net/edu/ebg/" target="_blank" class="keylink">word</a> in words:
7. print "%s\t%s" % (word, 1)

文件从STDIN读取文件。把单词切开,并把单词和词频输出STDOUT。Map脚本不会计算单词的总数,而是输出<word> 1。在我们的例子中,我们让随后的Reduce阶段做统计工作。

为了是脚本可执行,增加mapper.py的可执行权限

1. chmod +x hadoop-0.20.2/test/code/mapper.py

1.2 Reduce阶段:reducer.py

在这里,我们假设把文件保存到hadoop-0.20.2/test/code/reducer.py

01. #!/usr/bin/env python
02. from operator import itemgetter
03. import sys
04.  
05. current_word = None
06. current_count = 0
07. word = None
08.  
09. for line in sys.stdin:
10. line = line.strip()
11. word, count = line.split('\t'1)
12. try:
13. count = int(count)
14. except ValueError:  #count如果不是数字的话,直接忽略掉
15. continue
16. if current_word == word:
17. current_count += count
18. else:
19. if current_word:
20. print "%s\t%s" % (current_word, current_count)
21. current_count = count
22. current_word = word
23.  
24. if word == current_word:  #不要忘记最后的输出
25. print "%s\t%s" % (current_word, current_count)

文件会读取mapper.py 的结果作为reducer.py 的输入,并统计每个单词出现的总的次数,把最终的结果输出到STDOUT。

为了是脚本可执行,增加reducer.py的可执行权限

1. chmod +x hadoop-0.20.2/test/code/reducer.py

细节:split(chara, m),第二个参数的作用,下面的例子很给力

1. str = 'server=mpilgrim&ip=10.10.10.10&port=8080'
2. print str.split('='1)[0]  #1表示=只截一次
3. print str.split('='1)[1]
4. print str.split('=')[0]
5. print str.split('=')[1]

输出

1. server
2. mpilgrim&ip=10.10.10.10&port=8080
3. server
4. mpilgrim&ip 

1.3 测试代码(cat data | map | sort | reduce)

这里建议大家在提交给MapReduce job之前在本地测试mapper.py 和reducer.py脚本。否则jobs可能会成功执行,但是结果并非自己想要的。

功能性测试mapper.py 和 reducer.py

01. [rte@hadoop-0.20.2]$cd test/code
02. [rte@code]$echo "foo foo quux labs foo bar quux" | ./mapper.py
03. foo 1
04. foo 1
05. quux    1
06. labs    1
07. foo 1
08. bar 1
09. quux    1
10. [rte@code]$echo "foo foo quux labs foo bar quux" | ./mapper.py | sort -k1,1 | ./reducer.py
11. bar 1
12. foo 3
13. labs    1
14. quux    2

 细节:sort -k1,1  参数何意?

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

有时候经常使用sort来排序,需要预处理把需要排序的field语言在最前面。实际上这是

完全没有必要的,利用-k参数就足够了。

比如sort all

1. 1 4
2. 2 3
3. 3 2
4. 4 1
5. 5 0

如果sort -k 2的话,那么执行结果就是

1. 5 0
2. 4 1
3. 3 2
4. 2 3
5. 1 4

2. 在Hadoop上运行python代码

2.1 数据准备

下载以下三个文件的

Plain Text UTF-8 Plain Text UTF-8 Plain Text UTF-8

我把上面三个文件放到hadoop-0.20.2/test/datas/目录下

2.2 运行

把本地的数据文件拷贝到分布式文件系统HDFS中。

1. bin/hadoop dfs -copyFromLocal /test/datas  hdfs_in

查看

1. bin/hadoop dfs -ls

结果

1. drwxr-xr-x   - rte supergroup          0 2014-07-05 15:40 /user/rte/hdfs_in

查看具体的文件

1. bin/hadoop dfs -ls /user/rte/hdfs_in

执行MapReduce job

1. bin/hadoop jar contrib/streaming/hadoop-*streaming*.jar \
2. -file test/code/mapper.py     -mapper test/code/mapper.py \
3. -file test/code/reducer.py    -reducer test/code/reducer.py \
4. -input /user/rte/hdfs_in/*    -output /user/rte/hdfs_out

实例输出

\

查看输出结果是否在目标目录/user/rte/hdfs_out

1. bin/hadoop dfs -ls /user/rte/hdfs_out

输出

1. Found 2 items
2. drwxr-xr-x   - rte supergroup          0 2014-07-05 20:51 /user/rte/hdfs_out2/_logs
3. -rw-r--r--   2 rte supergroup     880829 2014-07-05 20:51 /user/rte/hdfs_out2/part-00000

查看结果

1. bin/hadoop dfs -cat /user/rte/hdfs_out2/part-00000

输出

\

以上已经达成目的了,但是可以利用python迭代器和生成器优化

3. 利用python的迭代器和生成器优化Mapper 和 Reducer代码

3.1 python中的迭代器和生成器

   看这

3.2 优化Mapper 和 Reducer代码

mapper.py

01. #!/usr/bin/env python
02. import sys
03. def read_input(file):
04. for line in file:
05. yield line.split()
06.  
07. def main(separator='\t'):
08. data = read_input(sys.stdin)
09. for words in data:
10. for word in words:
11. print "%s%s%d" % (word, separator, 1)
12.  
13. if __name__ == "__main__":
14. main()

reducer.py

01. #!/usr/bin/env python
02. from operator import itemgetter
03. from itertools import groupby
04. import sys
05.  
06. def read_mapper_output(file, separator = '\t'):
07. for line in file:
08. yield line.rstrip().split(separator, 1)
09.  
10. def main(separator = '\t'):
11. data = read_mapper_output(sys.stdin, separator = separator)
12. for current_word, group in groupby(data, itemgetter(0)):
13. try:
14. total_count = sum(int(count) for current_word, count in group)
15. print "%s%s%d" % (current_word, separator, total_count)
16. except valueError:
17. pass
18.  
19. if __name__ == "__main__":
20. main()<br>

细节:groupby

01. from itertools import groupby
02. from operator import itemgetter
03.  
04. things = [('2009-09-02'11),
05. ('2009-09-02'3),
06. ('2009-09-03'10),
07. ('2009-09-03'4),
08. ('2009-09-03'22),
09. ('2009-09-06'33)]
10.  
11. sss = groupby(things, itemgetter(0))
12. for key, items in sss:
13. print key
14. for subitem in items:
15. print subitem
16. print '-' 20

结果

01. >>>
02. 2009-09-02
03. ('2009-09-02'11)
04. ('2009-09-02'3)
05. --------------------
06. 2009-09-03
07. ('2009-09-03'10)
08. ('2009-09-03'4)
09. ('2009-09-03'22)
10. --------------------
11. 2009-09-06
12. ('2009-09-06'33)
13. --------------------

注 

groupby(things, itemgetter(0)) 以第0列为排序目标 groupby(things, itemgetter(1))以第1列为排序目标 groupby(things)以整行为排序目标

4. 参考

python中的split函数中的参数问题

Writing an Hadoop MapReduce Program in Python

shell的sort命令的-k参数 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值