hadoop與python
㈠ 如何在Hadoop環境下搭建python
搭建 Python 環境在 Hadoop 上的步驟如下:
安裝 Hadoop:在你的計算機上安裝 Hadoop。
安裝 Python:請確保你的計孫拿算機上已經安裝了 Python。
配置 Hadoop 環境:編輯 Hadoop 的配置文件,以確保 Hadoop 可以與 Python 配合使用。
安裝相關模塊:請安裝所需的 Python 模塊,以便在 Hadoop 環境下使用 Python。
測試灶行 Python 安裝:請運行一些測試腳本,以確保 Python 可以在 Hadoop 環境下正常工作。
這些步驟可以幫助你在 Hadoop 環境下搭建 Python。請注意,具體的步驟可能因 Hadoop 的版本和環境而異,請仔細查則辯搭看相關文檔。
㈡ 如何使用Python為Hadoop編寫一個簡單的MapRece程序
MichaelG.Noll在他的Blog中提到如何在Hadoop中用Python編寫MapRece程序,韓國的gogamza在其Bolg中也提到如何用C編汪瞎寫MapRece程序(我稍微修改了一下原程序,因為他的Map對單詞切分使用tab鍵)。我合並他們兩人的文章,也讓國內的Hadoop用戶能夠使用別的語言來編寫MapRece程序。首先您得配好您的Hadoop集群,這方面的介紹網上比較多,這兒給個鏈接(Hadoop學習筆記二安裝部署)。HadoopStreaming幫助返鋒我們用非Java的編程語言使用MapRece,Streaming用STDIN(標准輸入)和STDOUT(標准輸出)來和我們編寫的Map和Rece進行數據的交換數據。任何能夠使用STDIN和STDOUT都可以用來編寫MapRece程序,比如我們用Python的sys.stdin和sys.stdout,或者是C中的stdin和stdout。我們還是使用Hadoop的例子WordCount來做示範如何編寫MapRece,在WordCount的例子中漏陵晌我們要解決計算在一批文檔中每一個單詞的出現頻率。首先我們在Map程序中會接受到這批文檔每一行的數據,然後我們編寫的Map程序把這一行按空格切開成一個數組。並對這個數組遍歷按"1"用標準的輸出輸出來,代表這個單詞出現了一次。在Rece中我們來統計單詞的出現頻率。PythonCodeMap:mapper.py#!/usr/bin/envpythonimportsys#={}#inputcomesfromSTDIN(standardinput)forlineinsys.stdin:#=line.strip()#=filter(lambdaword:word,line.split())#:#writetheresultstoSTDOUT(standardoutput);##Recestep,i.e.theinputforrecer.py##tab-delimited;thetrivialwordcountis1print'%s\t%s'%(word,1)Rece:recer.py#!/usr/bin/#={}#.stdin:#=line.strip()#parsetheinputwegotfrommapper.pyword,count=line.split()#convertcount(currentlyastring)tointtry:count=int(count)word2count[word]=word2count.get(word,0)+countexceptValueError:#countwasnotanumber,sosilently#ignore/discardthislinepass#sortthewordslexigraphically;##thisstepisNOTrequired,wejustdoitsothatour##wordcountexamplessorted_word2count=sorted(word2count.items(),key=itemgetter(0))#writetheresultstoSTDOUT(standardoutput)forword,countinsorted_word2count:print'%s\t%s'%(word,count)CCodeMap:Mapper.c#include#include#include#include#defineBUF_SIZE2048#defineDELIM"\n"intmain(intargc,char*argv[]){charbuffer[BUF_SIZE];while(fgets(buffer,BUF_SIZE-1,stdin)){intlen=strlen(buffer);if(buffer[len-1]=='\n')buffer[len-1]=0;char*querys=index(buffer,'');char*query=NULL;if(querys==NULL)continue;querys+=1;/*nottoinclude'\t'*/query=strtok(buffer,"");while(query){printf("%s\t1\n",query);query=strtok(NULL,"");}}return0;}h>h>h>h>Rece:Recer.c#include#include#include#include#defineBUFFER_SIZE1024#defineDELIM"\t"intmain(intargc,char*argv[]){charstrLastKey[BUFFER_SIZE];charstrLine[BUFFER_SIZE];intcount=0;*strLastKey='\0';*strLine='\0';while(fgets(strLine,BUFFER_SIZE-1,stdin)){char*strCurrKey=NULL;char*strCurrNum=NULL;strCurrKey=strtok(strLine,DELIM);strCurrNum=strtok(NULL,DELIM);/*necessarytocheckerrorbut.*/if(strLastKey[0]=='\0'){strcpy(strLastKey,strCurrKey);}if(strcmp(strCurrKey,strLastKey)){printf("%s\t%d\n",strLastKey,count);count=atoi(strCurrNum);}else{count+=atoi(strCurrNum);}strcpy(strLastKey,strCurrKey);}printf("%s\t%d\n",strLastKey,count);/*flushthecount*/return0;}h>h>h>h>首先我們調試一下源碼:chmod+xmapper.pychmod+xrecer.pyecho"foofooquuxlabsfoobarquux"|./mapper.py|./recer.pybar1foo3labs1quux2g++Mapper.c-oMapperg++Recer.c-oRecerchmod+xMapperchmod+xRecerecho"foofooquuxlabsfoobarquux"|./Mapper|./你可能看到C的輸出和Python的不一樣,因為Python是把他放在詞典里了.我們在Hadoop時,會對這進行排序,然後相同的單詞會連續在標准輸出中輸出.在Hadoop中運行程序首先我們要下載我們的測試文檔wget頁面中摘下的用php編寫的MapRece程序,供php程序員參考:Map:mapper.php#!/usr/bin/php$word2count=array();//inputcomesfromSTDIN(standardinput)while(($line=fgets(STDIN))!==false){//$line=strtolower(trim($line));//$words=preg_split('/\W/',$line,0,PREG_SPLIT_NO_EMPTY);//increasecountersforeach($wordsas$word){$word2count[$word]+=1;}}//writetheresultstoSTDOUT(standardoutput)////Recestep,i.e.theinputforrecer.pyforeach($word2countas$word=>$count){//tab-delimitedecho$word,chr(9),$count,PHP_EOL;}?>Rece:mapper.php#!/usr/bin/php$word2count=array();//inputcomesfromSTDINwhile(($line=fgets(STDIN))!==false){//$line=trim($line);//parsetheinputwegotfrommapper.phplist($word,$count)=explode(chr(9),$line);//convertcount(currentlyastring)toint$count=intval($count);//sumcountsif($count>0)$word2count[$word]+=$count;}//sortthewordslexigraphically////thissetisNOTrequired,wejustdoitsothatour////wordcountexamplesksort($word2count);//writetheresultstoSTDOUT(standardoutput)foreach($word2countas$word=>$count){echo$word,chr(9),$count,PHP_EOL;}?>作者:馬士華發表於:2008-03-05
㈢ 如何使用Python為Hadoop編寫一個簡單的MapRece程序
在這個實例中,我將會向大家介紹如何使用Python 為 Hadoop編寫一個簡單的MapRece
程序。
盡管Hadoop 框架是使用Java編寫的但是我們仍然需要使用像C++、Python等語言來實現Hadoop程序。盡管Hadoop官方網站給的示常式序是使用Jython編寫並打包成Jar文件,這樣顯然造成了不便,其實,不一定非要這樣來實現,我們可以使用Python與Hadoop 關聯進行編程,看看位於/src/examples/python/WordCount.py 的例子,你將了解到我在說什麼。
我們想要做什麼?
我們將編寫一個簡單的 MapRece 程序,使用的是C-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的MapRece代碼
使用Python編寫MapRece代碼的技巧就在於我們使用了 HadoopStreaming 來幫助我們在Map 和 Rece間傳遞數據通過STDIN (標准輸入)和STDOUT (標准輸出).我們僅僅使用Python的sys.stdin來輸入數據,使用sys.stdout輸出數據,這樣做是因為HadoopStreaming會幫我們辦好其他事。這是真的,別不相信!
Map: mapper.py
將下列的代碼保存在/home/hadoop/mapper.py中,他將從STDIN讀取數據並將單詞成行分隔開,生成一個列表映射單詞與發生次數的關系:
注意:要確保這個腳本有足夠許可權(chmod +x /home/hadoop/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
# Rece step, i.e. the input for recer.py
#
# tab-delimited; the trivial word count is 1
print '%s\\t%s' % (word, 1)在這個腳本中,並不計算出單詞出現的總數,它將輸出 "<word> 1" 迅速地,盡管<word>可能會在輸入中出現多次,計算是留給後來的Rece步驟(或叫做程序)來實現。當然你可以改變下編碼風格,完全尊重你的習慣。
Rece: recer.py
將代碼存儲在/home/hadoop/recer.py 中,這個腳本的作用是從mapper.py 的STDIN中讀取結果,然後計算每個單詞出現次數的總和,並輸出結果到STDOUT。
同樣,要注意腳本許可權:chmod +x /home/hadoop/recer.py
#!/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 | rece)
我建議你在運行MapRece job測試前嘗試手工測試你的mapper.py 和 recer.py腳本,以免得不到任何返回結果
這里有一些建議,關於如何測試你的Map和Rece的功能:
——————————————————————————————————————————————
\r\n
# very basic test
hadoop@ubuntu:~$ echo "foo foo quux labs foo bar quux" | /home/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/hadoop/mapper.py | sort | /home/hadoop/recer.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/gutenberg/20417-8.txt | /home/hadoop/mapper.py
The 1
Project 1
Gutenberg 1
EBook 1
of 1
[...]
(you get the idea)
quux 2
quux 1
——————————————————————————————————————————————
在Hadoop平台上運行Python腳本
為了這個例子,我們將需要三種電子書:
The Outline of Science, Vol. 1 (of 4) by J. Arthur Thomson\r\n
The Notebooks of Leonardo Da Vinci\r\n
Ulysses by James Joyce
下載他們,並使用us-ascii編碼存儲 解壓後的文件,保存在臨時目錄,比如/tmp/gutenberg.
hadoop@ubuntu:~$ ls -l /tmp/gutenberg/
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
在我們運行MapRece job 前,我們需要將本地的文件復制到HDFS中:
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -FromLocal /tmp/gutenberg gutenberg
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls
Found 1 items
/user/hadoop/gutenberg <dir>
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls gutenberg
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
執行 MapRece job
現在,一切准備就緒,我們將在運行Python MapRece job 在Hadoop集群上。像我上面所說的,我們使用的是
HadoopStreaming 幫助我們傳遞數據在Map和Rece間並通過STDIN和STDOUT,進行標准化輸入輸出。
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.19.1-streaming.jar
-mapper /home/hadoop/mapper.py -recer /home/hadoop/recer.py -input gutenberg/*
-output gutenberg-output
在運行中,如果你想更改Hadoop的一些設置,如增加Rece任務的數量,你可以使用「-jobconf」選項:
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.19.1-streaming.jar
-jobconf mapred.rece.tasks=16 -mapper ...
一個重要的備忘是關於Hadoop does not honor mapred.map.tasks
這個任務將會讀取HDFS目錄下的gutenberg並處理他們,將結果存儲在獨立的結果文件中,並存儲在HDFS目錄下的
gutenberg-output目錄。
之前執行的結果如下:
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.19.1-streaming.jar
-mapper /home/hadoop/mapper.py -recer /home/hadoop/recer.py -input gutenberg/*
-output gutenberg-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% rece 0%
[...] INFO streaming.StreamJob: map 43% rece 0%
[...] INFO streaming.StreamJob: map 86% rece 0%
[...] INFO streaming.StreamJob: map 100% rece 0%
[...] INFO streaming.StreamJob: map 100% rece 33%
[...] INFO streaming.StreamJob: map 100% rece 70%
[...] INFO streaming.StreamJob: map 100% rece 77%
[...] INFO streaming.StreamJob: map 100% rece 100%
[...] INFO streaming.StreamJob: Job complete: job_200803031615_0021
[...] INFO streaming.StreamJob: Output: gutenberg-output hadoop@ubuntu:/usr/local/hadoop$
正如你所見到的上面的輸出結果,Hadoop 同時還提供了一個基本的WEB介面顯示統計結果和信息。
當Hadoop集群在執行時,你可以使用瀏覽器訪問 http://localhost:50030/ ,如圖:
檢查結果是否輸出並存儲在HDFS目錄下的gutenberg-output中:
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls gutenberg-output
Found 1 items
/user/hadoop/gutenberg-output/part-00000 <r 1> 903193 2007-09-21 13:00
hadoop@ubuntu:/usr/local/hadoop$
可以使用dfs -cat 命令檢查文件目錄
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -cat gutenberg-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插入的。
轉載僅供參考,版權屬於原作者。祝你愉快,滿意請採納哦