zoukankan      html  css  js  c++  java
  • 在Hadoop平台跑python脚本

    1、开发IDE,我使用的是PyCharm。

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

    3、Map阶段

    [root@mycentos ~]$ vim mapper.py
    
    #!/usr/bin/env python
    import sys
    
    for line in sys.stdin:
        line = line.strip()
        words = line.split()
        for word in words:
            print ("%s	%s") % (word, 1)

    程序说明:文件从STDIN读取文件。把单词切开,并把单词和词频输出STDOUT。Map脚本不会计算单词的总数,而是输出<word> 1。在我们的例子中,我们让随后的Reduce阶段做统计工作。

    设置执行权限

    chmod +x mapper.py

    3、Reduce阶段

    [root@mycentos ~]$ vim reduce.py
    
    #!/usr/bin/env python
    from operator import itemgetter
    import sys
    
    current_word = None
    current_count = 0
    word = None
    
    for line in sys.stdin:
        line = line.strip()
        word, count = line.split('	', 1)
        try:
            count = int(count)
        except ValueError:  #count如果不是数字的话,直接忽略掉
            continue
        if current_word == word:
            current_count += count
        else:
            if current_word:
                print ("%s	%s") % (current_word, current_count)
            current_count = count
            current_word = word
    
    if word == current_word:  #不要忘记最后的输出
        print ("%s	%s") % (current_word, current_count)

    程序说明:文件会读取mapper.py 的结果作为reducer.py 的输入,并统计每个单词出现的总的次数,把最终的结果输出到STDOUT。

    注意:split(chara, m),第二个参数的作用表示只截取一次。

    增加执行权限

    chmod +x reducer.py

    4、如何测试

    [root@mycentos ~]$echo "pib foo foo quux labs foo bar quux" | ./mapper.py | sort -k1,1 | ./reducer.py    #-k1 表示按key倒序输出

    5、如何在Hadoop上运行

    首先写一个脚本run.sh(因为代码较长,直接写不太方便)

    [root@mycentos ~]$ vim run.sh
    
    hadoop jar /home/hadoopuser/hadoop-2.6.0-cdh5.6.0/share/hadoop/tools/lib/hadoop-*streaming*.jar 
    -file /home/hadoopuser/mydoc/py/mapper.py       -mapper /home/hadoopuser/mydoc/py/mapper.py 
    -file /home/hadoopuser/mydoc/py/reduce.py       -reducer /home/hadoopuser/mydoc/py/reduce.py 
    -input /tmp/py/input/*  -output /tmp/py/output

    增加执行权限

    chmod +x run.sh

    6、运行结果

    would    2101
    wounded    21
    wrapped    9
    wrong.    17
    wronged    10
    year    80
    yelled    5
  • 相关阅读:
    UPD通信
    异常处理
    网络编程-套接字(socket)
    数据分析(一)
    爬虫存储库之mongodb数据库(四)
    爬虫请求库selenium(三)
    爬虫解析库beautifulsoup(二)
    爬虫简介与request库(一)
    flask框架数据库之SQLAlchemy
    flask框架(四)
  • 原文地址:https://www.cnblogs.com/hunttown/p/5809582.html
Copyright © 2011-2022 走看看