由于Hadoop Stream的存在,使得任何支持读写标准数据流的编程语言实现map和reduce操做成为了可能。python
为了方便测试map代码和reduce代码,下面给出一个Linux环境下的shell 命令:shell
cat inputFileName | python map.py | sort | python map.py > outputFileName
编程
能够轻松的在没有hadoop 环境的机器上进行测试。app
下面介绍,在Hadoop环境中的,如何用Python完成Map和Reduce两个任务的代码编写。编程语言
这里依然采用大部分讲述MapReduce文章中所采用的WordCount任务做为示例。改任务须要统计给的海量文档中,各类单词出现的次数,其实就是统计词频(tf)。oop
import sys for line in sys.stdin: words = line.strip().split() for word in words: print("{}\t{}".format(word, 1))
import sys word, curWord, wordCount = None, None, 0 for line in sys.stdin: word, count = line.strip().split('\t') count = int(count) if word == curWord: wordCount += count else: print("{}\t{}".format(word, wordCount)) curWord, wordCount = curWord, count if word and word == curWord: print("{}\t{}".format(word, wordCount))
能够在单机上执行前面所述的命令没有问题后,而后执行下面的shell命令测试
hadoop jar $HADOOP_STREAMING \ -D mapred.job.name="自定义的job名字" \ -D mapred.map.tasks=1024 \ -D mapred.reduce.tasks=1024 -files map.py \ -files reduce.py \ -mapper "python map.py" \ -reducer "python reduce.py" \ -input /user/rte/hdfs_in/* \ -output /user/rte/hdfs_out