python调用hadoop

一、MRJob

Mrjob是一个编写MapReduce任务的开源Python框架,它实际上对Hadoop Streaming的命令行进行了封装,因此接粗不到Hadoop的数据流命令行,使我们可以更轻松、快速的编写MapReduce任务。
Mrjob通过Python的yield机制将函数变成一个生成器,通过不断调用next()去实现key:value的初始化或运算操作。

#!/usr/bin/python 
## 注意不要用/usr/bin/env python
# -*- coding: utf-8 -*-
from mrjob.job import MRJob
import re
class MRwordCount(MRJob):
    def mapper(self, _, line):
        pattern=re.compile(r'(\W+)')
        for word in re.split(pattern=pattern,string=line):
            if word.isalpha():
                yield (word.lower(),1)
    def reducer(self, word, count):
        l=list(count)
        yield (word,sum(l))
if __name__ == '__main__':
    MRwordCount.run() #run()方法,开始执行MapReduce任务。

执行脚本

python /wordCount.py /test.txt -r hadoop hdfs:///input hdfs:///output

二、python代码调用MapReduce

使用python写MapReduce的“诀窍”是利用Hadoop流的API,通过STDIN(标准输入)、STDOUT(标准输出)在Map函数和Reduce函数之间传递数据。
我们唯一需要做的是利用Python的sys.stdin读取输入数据,并把我们的输出传送给sys.stdout。Hadoop流将会帮助我们处理别的任何事情。

map代码:

#!/usr/bin/python
## 注意不要用/usr/bin/env python
import sys
for line in sys.stdin:  # 遍历读入数据的每一行
    line = line.strip()  # 将行尾行首的空格去除
    words = line.split()  #按空格将句子分割成单个单词
    for word in words:
        print('%s\t%s' %(word, 1))

reduce.py代码:

#!/usr/bin/python
## 注意不要用/usr/bin/env python
from operator import itemgetter
import sys
current_word = None  # 为当前单词
current_count = 0  # 当前单词频数
word = None
for line in sys.stdin:
    words = line.strip()  # 去除字符串首尾的空白字符
    word, count = words.split('\t')  # 按照制表符分隔单词和数量
    try:
        count = int(count)  # 将字符串类型的‘1’转换为整型1
    except ValueError:
        continue
    if current_word == word:  # 如果当前的单词等于读入的单词
        current_count += count  # 单词频数加1
    else:
        if current_word:  # 如果当前的单词不为空则打印其单词和频数
            print('%s\t%s' %(current_word, current_count))
        current_count = count  # 否则将读入的单词赋值给当前单词,且更新频数
        current_word = word
if current_word == word:
    print('%s\t%s' %(current_word, current_count))

执行脚本:

hadoop jar /home/hadoop/hadoop-2.7.7/share/hadoop/tools/lib/hadoop-streaming-2.7.7.jar -files ./mapper.py,./reducer.py -mapper ./mapper.py -reducer ./reducer.py -input /input/* -output /output
``
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JPype是一个用于在Python调用Java代码的库。通过JPype,我们可以在Python中使用Java的各种功能和库,包括Hadoop。 要使用JPype调用Hadoop,首先需要确保已经安装了JPype库,并且已经配置好了Java环境。 下面是一个简单的示例代码,展示了如何使用JPype调用Hadoop的MapReduce任务: ```python import jpype # 启动JVM jpype.startJVM(jpype.getDefaultJVMPath()) # 导入Java类 Configuration = jpype.JClass('org.apache.hadoop.conf.Configuration') Job = jpype.JClass('org.apache.hadoop.mapreduce.Job') Path = jpype.JClass('org.apache.hadoop.fs.Path') # 创建Configuration对象 conf = Configuration() # 设置Hadoop配置参数 conf.set("fs.defaultFS", "hdfs://localhost:9000") conf.set("mapreduce.framework.name", "yarn") # 创建Job对象 job = Job(conf, "MyJob") # 设置Mapper和Reducer类 job.setMapperClass(MyMapper) job.setReducerClass(MyReducer) # 设置输入和输出路径 inputPath = Path("/input") outputPath = Path("/output") FileInputFormat.addInputPath(job, inputPath) FileOutputFormat.setOutputPath(job, outputPath) # 提交任务并等待完成 job.waitForCompletion(True) # 关闭JVM jpype.shutdownJVM() ``` 以上代码中,我们首先启动了JVM,然后导入了需要使用的Java类。接下来,创建了一个Configuration对象,并设置了Hadoop的配置参数。然后,创建了一个Job对象,并设置了Mapper和Reducer类,以及输入和输出路径。最后,提交任务并等待完成。最后,关闭JVM。 请注意,以上示例代码仅为演示JPype调用Hadoop的基本流程,具体的Mapper和Reducer类的实现需要根据实际需求进行编写。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值