Hadoop 实战之Streaming(十二)

本文介绍了在Hadoop伪分布式集群中使用Streaming进行数据处理的步骤。通过Python脚本`mapper.py`和`reducer.py`实现MapReduce操作,并利用`start.sh`启动集群。内容包括上传文本文件到HDFS,解决Linux下Python脚本执行问题,以及最终查看处理后的结果集。
摘要由CSDN通过智能技术生成

环境:Vmware 8.0 和ubuntu11.04

Hadoop 实战之Streaming(十二)---通过脚本使用Streaming

第一步: 首先在/home/tanglg1987目录下新建一个start.sh脚本文件,每次启动虚拟机都要删除/tmp目录下的全部文件,重新格式化namenode,代码如下:
sudo rm -rf /tmp/*
rm -rf /home/tanglg1987/hadoop-0.20.2/logs
hadoop namenode -format
hadoop datanode -format
start-all.sh
hadoop fs -mkdir input 
hadoop dfsadmin -safemode leave

第二步:给start.sh增加执行权限并启动hadoop伪分布式集群,代码如下:

chmod 777 /home/tanglg1987/start.sh
./start.sh 

运行过程如下:

第三步:上传本地文件到hdfs

在/home/tanglg1987/input 目录下新建两个文件file01.txt,file02.txt

file01.txt内容如下:

hello hadoop

file02.txt内容如下:

hello world

上传本地文件到hdfs:

hadoop fs -put /home/tanglg1987/file01.txt input
hadoop fs -put /home/tanglg1987/file02.txt input

第四步:新建一个mapper.py和reducer.py的Python文件

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)

reducer.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)

第五步:新建一个test.py的Python文件

解决Linux下运行Python脚本显示“: 没有那个文件或目录”的问题
我猜不少人都遇到过类似的问题:
在Windows下写好了一个python脚本,运行没问题
但放到Linux系统下就必须在命令行前加上一个python解释器才能运行
脚本开头的注释行已经指明了解释器的路径,也用chmod给了执行权限,但就是不能直接运行脚本。
比如这个脚本:
#!/usr/bin/env python
#-*- coding=utf-8 -*-
def main():
print('This is just a test!\r\n')
if __name__ == '__main__':
main()
按理说没错的,但为什么不能直接运行呢?
后来发现问题出在换行表示上……
Windows下,文本的换行是\r\n一同实现的,而*nix下则只用\n
所以我的第一行代码在Linux下就被识别为了:
#!/usr/bin/env python\r
很显然,系统不知道这个"python\r"是个什么东西……
知道了这个,解决方案就很显而易见了,写了一个自动替换换行标志的脚本:

#!/usr/bin/env python
#-*- coding=utf-8 -*-
import sys, os
def replace_linesep(file_name):
	if type(file_name) != str:
		raise ValueError
	new_lines = []
	
	#以读模式打开文件
	try:
		fobj_original = open(file_name, 'r')
	except IOError:
		print('Cannot read file %s!' % file_name)
		return False
	#逐行读取原始脚本
	print('Reading file %s' % file_name)
	line = fobj_original.readline()
	while line:
		if line[-2:] == '\r\n':
			new_lines.append(line[:-2] + '\n')
		else:
			new_lines.append(line)
		line = fobj_original.readline()
	fobj_original.close()
	
	#以写模式打开文件
	try:
		fobj_new = open(file_name, 'w')
	except IOError:
		print('Cannot write file %s!' % file_name)
		return False
	#逐行写入新脚本
	print('Writing file %s' % file_name)
	for new_line in new_lines:
		fobj_new.write(new_line)
	fobj_new.close()
	return True
		
def main():
	args = sys.argv
	if len(args) < 2:
		print('Please enter the file names as parameters follow this script.')
		os._exit(0)
	else:
		file_names = args[1:]
		for file_name in file_names:
			if replace_linesep(file_name):
				print('Replace for %s successfully!' % file_name)
			else:
				print('Replace for %s failed!' % file_name)
	os._exit(1)

if __name__ == '__main__':
	main()

第六步:新建一个replace.sh的shell文件

/home/tanglg1987/test/streaming/test.py *.py

运行过程如下:

第七步:编写一个名为:WordCountTest.sh的shell脚本

$HADOOP_HOME/bin/hadoop  jar $HADOOP_HOME/hadoop-0.20.2-streaming.jar -input input -output output -mapper /home/tanglg1987/test/streaming/mapper.py -reducer /home/tanglg1987/test/streaming/reducer.py 

第八步:给WordCountTest.sh增加执行权限并启动脚本,代码如下:

chmod 777 /home/tanglg1987/WordCountTest.sh
./WordCountTest

第九步:运行过程如下:

第十步:查看结果集,运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值