首页 Linux Hadoop札记:操作Python编写wordcount程序

Hadoop札记:操作Python编写wordcount程序

ASP站长网尝试着用3台虚拟机搭建了伪分布式系统,完整的搭建步骤等熟悉了整个分布式框架之后再写,今天写一下用python写wordcount程序(MapReduce任务)的具体步骤。
 
MapReduce任务以来HDFS存储和Yarn资源调度,所以执行MapReduce之前要先启动HDFS和Yarn。我们都知道MapReduce分Map阶段和Reduce阶段,这就需要我们 自己写Map阶段的处理方法和Reduce阶段的处理方法。
 
MapReduce也支持除Java之外的其他语言,但要依赖流处理包(Hadoop-streaming-2.7.4.jar),处理包不需要自己下载,hadoop本身带的就有,hadoop2.7的在hadoop-2.7.4/share/hadoop/tools/lib目录下,知道它所在的目录是因为只执行MapReduce命令的时候要指定hadoop-streaming-2.7.4.jar的位置。
 
接下来就是用python写Map的处理逻辑和Reduce的处理逻辑。wordcount是词频统计,要处理的原文本文件要上传到HDFS上,流程是原文本以流式方式传到Map函数,Map函数处理之后把结果传到Reduce函数,整个处理完后结果会保存在HDFS上,流式处理可以理解成文本一行一行的在原文件、Map函数、Reduce函数、结果文件之间流动处理。
 
原文本:
 
hello world
hello hadoop hadoop
nihao world
hello mapreduce
 
Map方法代码:
 
#!/usr/bin/python
import sys<br>
for line in sys.stdin:
    line = line.strip()
    words = line.split(' ')
    for word in words:
        print('%s\t%s'%(word,1))
 
Reduce方法代码:
 
#!/usr/bin/python
import sys
 
current_count = 0
current_word = None
 
for line in sys.stdin:
    line = line.strip()
    word, count = line.split('\t', 1)
    count = int(count)
    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
 
代码的逻辑都很简单,从标准输入按行读取处理数据,每行处理完print打印。
 
先在shell上测试一下:
 
#cat word.txt | ./mapper.py | sort
 
hadoop  1
hadoop  1
hello  1
hello  1
hello  1
mapreduce  1
nihao  1
world  1
world  1
 
sort是行之间按单词首字母排序,在MapReduce上sort过程hadoop会处理。
 
如果没有sort,结果是这样的:
 
#cat word.txt | ./mapper.py
 
hello  1
world  1
hello  1
hadoop  1
hadoop  1
nihao  1
world  1
hello  1
mapreduce  1
 
#cat word.txt | ./mapper.py | sort |./reducer.py
 
hadoop  2
hello  3
mapreduce  1
nihao  1
 
测试完没问题后就可以用MapReduce来执行了。
 
输入命令:
 
hadoop jar hadoop-streaming-2.7.4.jar \
 
-input /wordcount/word.txt \
 
-output /wordcount/out \
 
-mapper /home/hadoop/apps/hadoop-2.7.4/file/wordcount_python/mapper.py \
 
-reducer /home/hadoop/apps/hadoop-2.7.4/file/wordcount_python/reducer.py

关于作者: dawei

【声明】:九江站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

热门文章