前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何使用Python为Hadoop编写一个简单的MapReduce程序

如何使用Python为Hadoop编写一个简单的MapReduce程序

作者头像
MachineLP
发布2018-01-09 15:33:55
2.1K0
发布2018-01-09 15:33:55
举报
文章被收录于专栏:小鹏的专栏小鹏的专栏

How to Install Hadoop in Stand-Alone Mode on Ubuntu 16.04

如何使用Python 为 Hadoop编写一个简单的MapReduce程序。

尽管Hadoop框架是使用Java编写的但是我们仍然需要使用像C++、Python等语言来实现Hadoop程序。尽管Hadoop官方网站给的示例程序是使用Jython编写并打包成Jar文件,这样显然造成了不便,其实,不一定非要这样来实现,我们可以使用Python与Hadoop 关联进行编程,看看位于/src/examples/python/WordCount.py  的例子,你将了解到我在说什么。

我们想要做什么?

我们将编写一个简单的MapReduce 程序,使用的是Python,而不是Jython编写后打包成jar包的程序。

我们的这个例子将模仿 WordCount 并使用Python来实现,例子通过读取文本文件来统计出单词的出现次数。结果也以文本形式输出,每一行包含一个单词和单词出现的次数,两者中间使用制表符来想间隔。

先决条件

编写这个程序之前,你学要架设好Hadoop 集群,这样才能不会在后期工作抓瞎。如果你没有架设好,那么在后面有个简明教程来教你在Ubuntu Linux 上搭建(同样适用于其他发行版linux、unix)

如何使用Hadoop Distributed File System (HDFS)在Ubuntu Linux 建立单节点的 Hadoop 集群

如何使用Hadoop Distributed File System (HDFS)在Ubuntu Linux 建立多节点的 Hadoop 集群

Python的MapReduce代码

使用Python编写MapReduce代码的技巧就在于我们使用了 HadoopStreaming 来帮助我们在Map 和 Reduce间传递数据通过STDIN (标准输入)和STDOUT (标准输出).我们仅仅使用Python的sys.stdin来输入数据,使用sys.stdout输出数据,这样做是因为HadoopStreaming会帮我们办好其他事。这是真的,别不相信!

Map: mapper.py

将下列的代码保存在/home/liupeng/hadoop/mapper.py中,他将从STDIN读取数据并将单词成行分隔开,生成一个列表映射单词与发生次数的关系:

注意:要确保这个脚本有足够权限(chmod +x /home/liupeng/hadoop/mapper.py)。

代码语言:javascript
复制
#!/usr/bin/env python
 
import sys
 
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
    line = line.strip()
# split the line into words
    words = line.split()
# increase counters
for word in words:
# write the results to STDOUT (standard output);
# what we output here will be the input for the
# Reduce step, i.e. the input for reducer.py
#
# tab-delimited; the trivial word count is 1
print '%s\\t%s' % (word, 1)

在这个脚本中,并不计算出单词出现的总数,它将输出 "<word> 1" 迅速地,尽管<word>可能会在输入中出现多次,计算是留给后来的Reduce步骤(或叫做程序)来实现。当然你可以改变下编码风格,完全尊重你的习惯。

Reduce: reducer.py

将代码存储在/home/liupeng/hadoop/reducer.py 中,这个脚本的作用是从mapper.py 的STDIN中读取结果,然后计算每个单词出现次数的总和,并输出结果到STDOUT。

同样,要注意脚本权限:chmod +x /home/liupeng/hadoop/reducer.py

代码语言:javascript
复制
#!/usr/bin/env python
 
from operator import itemgetter
import sys
 
# maps words to their counts
word2count = {}
 
# input comes from STDIN
for line in sys.stdin:
# remove leading and trailing whitespace
    line = line.strip()
 
# parse the input we got from mapper.py
    word, count = line.split('\\t', 1)
# convert count (currently a string) to int
try:
        count = int(count)
        word2count[word] = word2count.get(word, 0) + count
except ValueError:
# count was not a number, so silently
# ignore/discard this line
pass
 
# sort the words lexigraphically;
#
# this step is NOT required, we just do it so that our
# final output will look more like the official Hadoop
# word count examples
sorted_word2count = sorted(word2count.items(), key=itemgetter(0))
 
# write the results to STDOUT (standard output)
for word, count in sorted_word2count:
print '%s\\t%s'% (word, count)

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

我建议你在运行MapReduce job测试前尝试手工测试你的mapper.py 和 reducer.py脚本,以免得不到任何返回结果

这里有一些建议,关于如何测试你的Map和Reduce的功能:

代码语言:javascript
复制

——————————————————————————————————————————————
 # very basic test
 hadoop@ubuntu:~$ echo "foo foo quux labs foo bar quux" | /home/liupeng/hadoop/mapper.py
 foo     1
 foo     1
 quux    1
 labs    1
 foo     1
 bar     1
——————————————————————————————————————————————
 hadoop@ubuntu:~$ echo "foo foo quux labs foo bar quux" | /home/liupeng/hadoop/mapper.py | sort | /home/liupeng/hadoop/reducer.py
 bar     1
 foo     3
 labs    1
——————————————————————————————————————————————

 # using one of the ebooks as example input
 # (see below on where to get the ebooks)
 hadoop@ubuntu:~$ cat /tmp/liupeng/20417-8.txt | /home/liupeng/hadoop/mapper.py
 The     1
 Project 1
 Gutenberg       1
 EBook   1
 of      1
 [...] 
 (you get the idea)

 quux    2

 quux    1  

—————————————————————————————————————————————

在Hadoop平台上运行Python脚本为了这个例子,我们将需要三种电子书:

下载他们,并使用us-ascii编码存储 解压后的文件,保存在临时目录,比如/tmp/liupeng.

代码语言:javascript
复制
 hadoop@ubuntu:~$ ls -l /tmp/liupeng/
 total 3592
 -rw-r--r-- 1 hadoop hadoop  674425 2007-01-22 12:56 20417-8.txt
 -rw-r--r-- 1 hadoop hadoop 1423808 2006-08-03 16:36 7ldvc10.txt
 -rw-r--r-- 1 hadoop hadoop 1561677 2004-11-26 09:48 ulyss12.txt
 hadoop@ubuntu:~$

复制本地数据到HDFS

在我们运行MapReduce job 前,我们需要将本地的文件复制到HDFS中:

 hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -copyFromLocal /tmp/liupeng liupeng
 hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls
 Found 1 items
 /user/hadoop/liupeng  <dir>
 hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls liupeng
 Found 3 items
 /user/hadoop/gutenberg/20417-8.txt      <r 1>   674425
 /user/hadoop/gutenberg/7ldvc10.txt      <r 1>   1423808
 /user/hadoop/gutenberg/ulyss12.txt      <r 1>   1561677

执行 MapReduce job

现在,一切准备就绪,我们将在运行Python MapReduce job 在Hadoop集群上。像我上面所说的,我们使用的是
HadoopStreaming 帮助我们传递数据在Map和Reduce间并通过STDIN和STDOUT,进行标准化输入输出。


hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.8.1.jar 
    -mapper /home/liupeng/hadoop/mapper.py -reducer /home/liupeng/hadoop/reducer.py 
    -input liupeng/* -output liupeng-output
在运行中,如果你想更改Hadoop的一些设置,如增加Reduce任务的数量,你可以使用“-jobconf”选项: 
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.8.1.jar
   

-jobconf mapred.reduce.tasks=16 -mapper ...

一个重要的备忘是关于Hadoop does not honor mapred.map.tasks

这个任务将会读取HDFS目录下的gutenberg并处理他们,将结果存储在独立的结果文件中,并存储在HDFS目录下的

gutenberg-output目录。

之前执行的结果如下:

代码语言:javascript
复制
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.8.1.jar 
    -mapper /home/liupeng/hadoop/mapper.py -reducer /home/liupeng/hadoop/reducer.py 
    -input liupeng/* -output liupeng-output

additionalConfSpec_:null

null=@@@userJobConfProps_.get(stream.shipped.hadoopstreaming

packageJobJar: [/usr/local/hadoop-datastore/hadoop-hadoop/hadoop-unjar54543/]

[] /tmp/streamjob54544.jar tmpDir=null

[...] INFO mapred.FileInputFormat: Total input paths to process : 7

[...] INFO streaming.StreamJob: getLocalDirs(): [/usr/local/hadoop-datastore/hadoop-hadoop/mapred/local]

[...] INFO streaming.StreamJob: Running job: job_200803031615_0021

[...]

[...] INFO streaming.StreamJob: map 0% reduce 0%

[...] INFO streaming.StreamJob: map 43% reduce 0%

[...] INFO streaming.StreamJob: map 86% reduce 0%

[...] INFO streaming.StreamJob: map 100% reduce 0%

[...] INFO streaming.StreamJob: map 100% reduce 33%

[...] INFO streaming.StreamJob: map 100% reduce 70%

[...] INFO streaming.StreamJob: map 100% reduce 77%

[...] INFO streaming.StreamJob: map 100% reduce 100%

[...] INFO streaming.StreamJob: Job complete: job_200803031615_0021

[...] INFO streaming.StreamJob: Output: liupeng-output hadoop@ubuntu:/usr/local/hadoop$

正如你所见到的上面的输出结果,Hadoop 同时还提供了一个基本的WEB接口显示统计结果和信息。

当Hadoop集群在执行时,你可以使用浏览器访问 http://localhost:50030/  ,如图:

检查结果是否输出并存储在HDFS目录下的gutenberg-output中:

代码语言:js
复制
 hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls liupeng-output
 Found 1 items
 /user/hadoop/liupeng-output/part-00000     <r 1>   903193  2007-09-21 13:00
 hadoop@ubuntu:/usr/local/hadoop$ 

可以使用dfs -cat 命令检查文件目录

代码语言:js
复制
 hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -cat liupeng-output/part-00000
 "(Lo)cra"       1
 "1490   1
 "1498," 1
 "35"    1
 "40,"   1
 "A      2
 "AS-IS".        2
 "A_     1
 "Absoluti       1
 [...]
 hadoop@ubuntu:/usr/local/hadoop$

注意比输出,上面结果的(")符号不是Hadoop插入的。

改善Mapper 和 Reducer 使用Python的iterators 和 generators

请参考:Python iterators and generators

http://www.michael-noll.com/wiki/Writing_An_Hadoop_MapReduce_Program_In_Python#What_we_want_to_do

代码语言:javascript
复制
请参考:
(1) http://www.cnblogs.com/end/archive/2012/08/13/2636175.html
(2) https://www.bbsmax.com/A/nAJvA3eQzr/
(3) https://www.digitalocean.com/community/tutorials/how-to-install-hadoop-in-stand-alone-mode-on-ubuntu-16-04
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年10月07日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • How to Install Hadoop in Stand-Alone Mode on Ubuntu 16.04
    • Map: mapper.py
      • Reduce: reducer.py
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档