hadoop调用python算法_使用Python实现Hadoop MapReduce程序
根据上面两篇文章,下面是我在自己的ubuntu上的运行过程。文字基本采用博文使用Python实现Hadoop MapReduce程序, 打字很浪费时间滴。
在这个实例中,我将会向大家介绍如何使用Python 为 Hadoop编写一个简单的MapReduce程序。
尽管Hadoop 框架是使用Java编写的但是我们仍然需要使用像C++、Python等语言来实现
Hadoop程序。尽管Hadoop官方网站给的示例程序是使用Jython编写并打包成Jar文件,这样显然造成了不便,其实,不一定非要这样来实现,
我们可以使用Python与Hadoop 关联进行编程,看看位于/src/examples/python/WordCount.py
的例子,你将了解到我在说什么。
我们想要做什么?
我们将编写一个简单的 MapReduce 程序,使用的是C-Python,而不是Jython编写后打包成jar包的程序。
我们的这个例子将模仿 WordCount 并使用Python来实现,例子通过读取文本文件来统计出单词的出现次数。结果也以文本形式输出,每一行包含一个单词和单词出现的次数,两者中间使用制表符来想间隔。
先决条件
编写这个程序之前,你学要架设好Hadoop 集群,这样才能不会在后期工作抓瞎。如果你没有架设好,那么在后面有个简明教程来教你在Ubuntu Linux 上搭建(同样适用于其他发行版linux、unix)
如何在Ubuntu Linux 上搭建hadoop的单节点模式和伪分布模式,请参阅博文Ubuntu上搭建Hadoop环境(单机模式+伪分布模式)
Python的MapReduce代码
使用Python编写MapReduce代码的技巧就在于我们使用了 HadoopStreaming 来帮助我们在Map 和
Reduce间传递数据通过STDIN (标准输入)和STDOUT
(标准输出).我们仅仅使用Python的sys.stdin来输入数据,使用sys.stdout输出数据,这样做是因为
HadoopStreaming会帮我们办好其他事。这是真的,别不相信!
Map: mapper.py
将下列的代码保存在/usr/local/hadoop/mapper.py中,他将从STDIN读取数据并将单词成行分隔开,生成一个列表映射单词与发生次数的关系:
注意:要确保这个脚本有足够权限(chmod +x mapper.py)。
#!/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)
在这个脚本中,并不计算出单词出现的总数,它将输出 " 1"
迅速地,尽管可能会在输入中出现多次,计算是留给后来的Reduce步骤(或叫做程序)来实现。当然你可以改变下编码风格,完全
尊重你的习惯。Reduce: reducer.py
将代码存储在/usr/local/hadoop/reducer.py 中,这个脚本的作用是从mapper.py 的STDIN中读取结果,然后计算每个单词出现次数的总和,并输出结果到STDOUT。
同样,要注意脚本权限:chmod +x reducer.py
#!/usr/bin/env python
from operator import itemgetter
import sys
current_word = None
current_count = 0
word = None
# 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)
except ValueError:
# count was not a number, so silently
# ignore/discard this line
continue
# this IF-switch only works because Hadoop sorts map output
# by key (here: word) before it is passed to the reducer
if current_word == word:
current_count += count
else:
if current_word:
# write result to STDOUT
print '%s\t%s' % (current_word, current_count)
current_count = count
current_word = word
# do not forget to output the last word if needed!
if current_word == word:
print '%s\t%s' % (current_word, current_count)
测试你的代码(cat data | map | sort | reduce)
我建议你在运行MapReduce job测试前尝试手工测试你的mapper.py 和 reducer.py脚本,以免得不到任何返回结果
这里有一些建议,关于如何测试你的Map和Reduce的功能:
hadoop@derekUbun:/usr/local/hadoop$ echo "foo foo quux labs foo bar quux" | ./mapper.py
foo 1
foo 1
quux 1
labs 1
foo 1
bar 1
quux 1
hadoop@derekUbun:/usr/local/hadoop$ echo "foo foo quux labs foo bar quux" |./mapper.py | sort |./reducer.py
bar 1
foo 3
labs 1
quux 2
# using one of the ebooks as example input
# (see below on where to get the ebooks)
hadoop@derekUbun:/usr/local/hadoop$ cat book/book.txt |./mapper.pysubscribe 1
to 1
our 1
email 1
newsletter 1
to 1
hear 1
about 1
new 1
eBooks. 1
在Hadoop平台上运行Python脚本
为了这个例子,我们将需要一本电子书,把它放在/usr/local/hadpoop/book/book.txt之下
hadoop@derekUbun:/usr/local/hadoop$ ls -l book
总用量 636
-rw-rw-r-- 1 derek derek 649669 3月 12 12:22 book.txt
复制本地数据到HDFS
在我们运行MapReduce job 前,我们需要将本地的文件复制到HDFS中:
hadoop@derekUbun:/usr/local/hadoop$ hadoop dfs -copyFromLocal /usr/local/hadoop/book book
hadoop@derekUbun:/usr/local/hadoop$ hadoop dfs -ls
Found 3 items
drwxr-xr-x - hadoop supergroup 0 2013-03-12 15:56 /user/hadoop/book
执行 MapReduce job现在,一切准备就绪,我们将在运行Python MapReduce job
在Hadoop集群上。像我上面所说的,我们使用的是HadoopStreaming
帮助我们传递数据在Map和Reduce间并通过STDIN和STDOUT,进行标准化输入输出。
hadoop@derekUbun:/usr/local/hadoop$hadoop jar contrib/streaming/hadoop-streaming-1.1.2.jar
-mapper /usr/local/hadoop/mapper.py
-reducer /usr/local/hadoop/reducer.py
-input book/*
-output book-output
在运行中,如果你想更改Hadoop的一些设置,如增加Reduce任务的数量,你可以使用“-jobconf”选项:
hadoop@derekUbun:/usr/local/hadoop$hadoop jar contrib/streaming/hadoop-streaming-1.1.2.jar
-jobconf mapred.reduce.tasks=4
-mapper /usr/local/hadoop/mapper.py
-reducer /usr/local/hadoop/reducer.py
-input book/*
-output book-output
如果上面两个运行出错,请参考下面一段代码。注意,重新运行,需要删除dfs中的output文件
bin/hadoop jar contrib/streaming/hadoop-streaming-1.1.2.jar
-mapper task1/mapper.py
-file task1/mapper.py
-reducer task1/reducer.py
-file task1/reducer.py
-input url
-output url-output
-jobconf mapred.reduce.tasks=3
一个重要的备忘是关于Hadoop does not honor mapred.map.tasks 这个任务将会读取HDFS目录下的book并处理他们,将结果存储在独立的结果文件中,并存储在HDFS目录下的book-output目录。之前执行的结果如下:
hadoop@derekUbun:/usr/local/hadoop$ hadoop jar contrib/streaming/hadoop-streaming-1.1.2.jar -jobconf mapred.reduce.tasks=4 -mapper /usr/local/hadoop/mapper.py -reducer /usr/local/hadoop/reducer.py -input book/* -output book-output
13/03/12 16:01:05 WARN streaming.StreamJob: -jobconf option is deprecated, please use -D instead.
packageJobJar: [/usr/local/hadoop/tmp/hadoop-unjar4835873410426602498/] [] /tmp/streamjob5047485520312501206.jar tmpDir=null
13/03/12 16:01:06 INFO util.NativeCodeLoader: Loaded the native-hadoop library
13/03/12 16:01:06 WARN snappy.LoadSnappy: Snappy native library not loaded
13/03/12 16:01:06 INFO mapred.FileInputFormat: Total input paths to process : 1
13/03/12 16:01:06 INFO streaming.StreamJob: getLocalDirs(): [/usr/local/hadoop/tmp/mapred/local]
13/03/12 16:01:06 INFO streaming.StreamJob: Running job: job_201303121448_0010
13/03/12 16:01:06 INFO streaming.StreamJob: To kill this job, run:
13/03/12 16:01:06 INFO streaming.StreamJob: /usr/local/hadoop/libexec/../bin/hadoop job -Dmapred.job.tracker=localhost:9001 -kill job_201303121448_0010
13/03/12 16:01:06 INFO streaming.StreamJob: Tracking URL: http://localhost:50030/jobdetails.jsp?jobid=job_201303121448_0010
13/03/12 16:01:07 INFO streaming.StreamJob: map 0% reduce 0%
13/03/12 16:01:10 INFO streaming.StreamJob: map 100% reduce 0%
13/03/12 16:01:17 INFO streaming.StreamJob: map 100% reduce 8%
13/03/12 16:01:18 INFO streaming.StreamJob: map 100% reduce 33%
13/03/12 16:01:19 INFO streaming.StreamJob: map 100% reduce 50%
13/03/12 16:01:26 INFO streaming.StreamJob: map 100% reduce 67%
13/03/12 16:01:27 INFO streaming.StreamJob: map 100% reduce 83%
13/03/12 16:01:28 INFO streaming.StreamJob: map 100% reduce 100%
13/03/12 16:01:29 INFO streaming.StreamJob: Job complete: job_201303121448_0010
13/03/12 16:01:29 INFO streaming.StreamJob: Output: book-output
hadoop@derekUbun:/usr/local/hadoop$
如你所见到的上面的输出结果,Hadoop 同时还提供了一个基本的WEB接口显示统计结果和信息。
当Hadoop集群在执行时,你可以使用浏览器访问 http://localhost:50030/ :
检查结果是否输出并存储在HDFS目录下的book-output中:
hadoop@derekUbun:/usr/local/hadoop$ hadoop dfs -ls book-output
Found 6 items
-rw-r--r-- 2 hadoop supergroup 0 2013-03-12 16:01 /user/hadoop/book-output/_SUCCESS
drwxr-xr-x - hadoop supergroup 0 2013-03-12 16:01 /user/hadoop/book-output/_logs
-rw-r--r-- 2 hadoop supergroup 33 2013-03-12 16:01 /user/hadoop/book-output/part-00000
-rw-r--r-- 2 hadoop supergroup 60 2013-03-12 16:01 /user/hadoop/book-output/part-00001
-rw-r--r-- 2 hadoop supergroup 54 2013-03-12 16:01 /user/hadoop/book-output/part-00002
-rw-r--r-- 2 hadoop supergroup 47 2013-03-12 16:01 /user/hadoop/book-output/part-00003
hadoop@derekUbun:/usr/local/hadoop$
可以使用dfs -cat 命令检查文件目录
hadoop@derekUbun:/usr/local/hadoop$ hadoop dfs -cat book-output/part-00000
about 1
eBooks. 1
the 1
to 2
hadoop@derekUbun:/usr/local/hadoop$
下面是原英文作者mapper.py和reducer.py的两个修改版本:
mapper.py
#!/usr/bin/env python
"""A more advanced Mapper, using Python iterators and generators."""
import sys
def read_input(file):
for line in file:
# split the line into words
yield line.split()
def main(separator='\t'):
# input comes from STDIN (standard input)
data = read_input(sys.stdin)
for words in data:
# 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
for word in words:
print '%s%s%d' % (word, separator, 1)
if __name__ == "__main__":
main()
reducer.py
#!/usr/bin/env python
"""A more advanced Reducer, using Python iterators and generators."""
from itertools import groupby
from operator import itemgetter
import sys
def read_mapper_output(file, separator='\t'):
for line in file:
yield line.rstrip().split(separator, 1)
def main(separator='\t'):
# input comes from STDIN (standard input)
data = read_mapper_output(sys.stdin, separator=separator)
# groupby groups multiple word-count pairs by word,
# and creates an iterator that returns consecutive keys and their group:
# current_word - string containing a word (the key)
# group - iterator yielding all ["", ""] items
for current_word, group in groupby(data, itemgetter(0)):
try:
total_count = sum(int(count) for current_word, count in group)
print "%s%s%d" % (current_word, separator, total_count)
except ValueError:
# count was not a number, so silently discard this item
pass
if __name__ == "__main__":
main()
hadoop调用python算法_使用Python实现Hadoop MapReduce程序相关推荐
- java python算法_用Python,Java和C ++示例解释的排序算法
java python算法 什么是排序算法? (What is a Sorting Algorithm?) Sorting algorithms are a set of instructions t ...
- 第一章 第一节:Python基础_认识Python
Python基础入门(全套保姆级教程) 第一章 第一节:Python基础_认识Python 1. 什么是编程 通俗易懂,编程就是用代码编写程序,编写程序有很多种办法,像c语言,javaPython语言 ...
- Python可以调用Gpu吗_加快Python算法的四个方法:Numba篇
CDA数据分析师 出品 相信大家在做一些算法经常会被庞大的数据量所造成的超多计算量需要的时间而折磨的痛苦不已,接下来我们围绕四个方法来帮助大家加快一下Python的计算时间,减少大家在算法上的等待时间 ...
- java python算法_用Java,Python和C ++示例解释的搜索算法
java python算法 什么是搜索算法? (What is a Search Algorithm?) This kind of algorithm looks at the problem of ...
- 按键精灵调用python插件_【Python 教程】使用 Python 和大漠插件进行文字识别
家里有一台win7系统的电脑,平时可以用来玩玩游戏消磨时间.但是有时候有一些重复的操作实在是无趣,所以打算写个脚本,让其自动化执行. 最终的目标就是把游戏里一些常用的操作都集合到脚本中去,且无序随机执 ...
- python调用usb设备_用Python与USB设备通信
假设您使用Linux和libusb-1.0作为PyUSB的后端库.// Detach a kernel driver from an interface. // If successful, you ...
- python扫雷 高级算法_利用Python实现自动扫雷
自动扫雷一般分为两种,一种是读取内存数据,而另一种是通过分析图片获得数据,并通过模拟鼠标操作,这里我用的是第二种方式. 一.准备工作 我的版本是 python 3.6.1 python的第三方库: w ...
- python调用接口查询_基于Python的苹果序列号官网查询接口调用代码实例
1.[代码][Python]代码 #!/usr/bin/python # -*- coding: utf-8 -*- import json, urllib from urllib import ur ...
- python调用chrome插件_使用Python开发chrome插件
标签: 谷歌Chrome插件是使用HTML.JavaScript和CSS编写的.如果你之前从来没有写过Chrome插件,我建议你读一下这个.在这篇教程中,我们将教你如何使用Python代替JavaSc ...
最新文章
- R语言主成分分析(Principle Component Analysis、PCA)
- 基于 python + WebDriverAgent 的“跳一跳”小程序高分教程
- 一文看懂全球半导体格局
- 西电计算机组装实验报告,西电模电实验报告(共7篇).docx
- 什么命令看服务器系统,查看linux系统版本可以使用什么命令_网站服务器运行维护...
- 一、select查询
- [渝粤教育] 潍坊职业学院 化工安全技术 参考 资料
- linux 添加环境变量(php为例)
- 教育大数据隐私保护机制与技术研究
- 蔡高厅老师 - 高等数学阅读笔记 - 02 - 极限(06 、07、08、09、10、11、12)
- Android 对ScrollView滚动监听,实现美团、大众点评的购买悬浮效果
- 先有鸡还是先有蛋? 加拿大科学家揭开谜底
- 想通过C++寻找后端开发工作如何提升自己?
- C陷阱与缺陷阅读笔记(上)
- IANA已注册的TCP/UDP/SCTP/DCCP传输协议端口及服务名称
- Python七天快速入门——第一天
- Qiime2+Origin绘制稀释曲线
- gcc: buildin函数: __builtin_unreachable __builtin_constant_p;__atomic_load_n
- 二叉树的构造以及基本操作
- android 集成高德地图打包后报 key-location Error, ErrCode:7 的问题