mapreduce python编程实例

2023-05-16

mapreduce python编程实例

1 - mapreduce使用python  WordCount实例
1.1 - mapper函数使用
vi mapper.py
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper.py

import sys
for line in sys.stdin:   #读取标准输入
    line = line.strip()  #删除前导和尾随空白
     words = line.split() #用split讲该行的单词分割成列表,每个单词就时一个列表项目,split的默认参数是空格,所以不传递任何参数时分割空格,在英文中也就等同于分割单词
    for word in words:
        print'%s\t%s'%(word,1)
 
[root@lsn-linux python]# echo "foo foo quux labs foo bar quux" |python /hadoop/hadoop-2.6.0/python/mapper.py
foo     1
foo     1
quux    1
labs    1
foo     1
bar     1
quux    1


2.2 - reduce函数使用
vim reduce.py
 #!/usr/bin/python
 #_*_ coding:utf-8 _*_
 #Filename:reduce.py
 
 from operator import itemgetter    //排序
 import sys
 
 word2count = {}   #定义一个字典
 
 for line in sys.stdin:
     line = line.strip()
     word,count = line.split('\t',1)
     try:
         count = int(count)
         word2count[word] = word2count.get(word,0)+count   #word2count.get(word,0),查找word键值,如果不存在返回0,如果存在返回键值
     except ValueError:
         pass
 
 sorted_word2count = sorted(word2count.items(),key=itemgetter(0)) #用word2count.items()的第一个项目进行排序

 for word,count in sorted_word2count:
     print'%s\t%s'%(word,count)
 
 [root@lsn-linux python]# echo "foo foo quux labs foo bar quux"|python mapper.py|python reduce.py 
bar     1
foo     3
labs    1
quux    2




1.3 - 在mapreduce执行
拷贝./share/hadoop/tools/lib/hadoop-streaming-2.6.0.jar到hadoop目录
赋予脚本执行权限,否则会报Cannot run program "/hadoop/hadoop-2.6.0/python/mapper.py": error=13, Permission denied错误
chmod +x -R python


hadoop jar hadoop-streaming-2.6.0.jar -mapper /hadoop/hadoop-2.6.0/python/mapper.py -reducer /hadoop/hadoop-2.6.0/python/reduce.py -input /testin/* -output /testout


----------------------------------------------------------------------------------------------------------------------------------------------------------------------


3 -  web访问日志分析
日志类型:
175.44.19.36 - - [29/Sep/2013:00:10:57 +0800] "GET /mapreduce-nextgen/client-codes/ HTTP/1.1" 200 25470 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)"
112.111.183.57 - - [29/Sep/2013:00:10:58 +0800] "POST /wp-comments-post.php HTTP/1.1" 302 513 "http://dongxicheng.org/search-engine/scribe-intro/" "Mozilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0"
5.63.145.70 - - [29/Sep/2013:00:11:03 +0800] "HEAD / HTTP/1.1" 200 221 "-" "checks.panopta.com"


2.1 - 统计访问ip地址数目
mapper实现--正则表达式
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper_3_1.py
import re
import sys


for line in sys.stdin:
     line = line.strip()
     words=re.match('(\d{1,3}\.){3}\d{1,3}',line).group()
     words = words.split('\n')
     for i in range(0,len(words)):
         print'%s\t%s'%(words[i],1)
         
mapper实现--字符串
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper_3_1_1.py
import sys
for line in sys.stdin:
     line = line.strip()
     words=line[:line.find(' ')]
     words = words.split('\n')
     for i in range(0,len(words)):
         print'%s\t%s'%(words[i],1)


reduce与之前一样
                                   
2.2 - 统计目录访问次数(/mapreduce-nextgen/client-codes/)
mapper实现--filter(lambda)打印
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper_3_2.py
import sys
for line in sys.stdin:
    line = line.strip()
    if line.find('GET')!=-1:
        words=line[line.find('GET')+3:line.find('HTTP')]
    # if line.find('POST')!=-1:
    elif line.find('HEAD')!=-1:
        words=line[line.find('HEAD')+4:line.find('HTTP')]
    else:
        words=line[line.find('POST')+4:line.find('HTTP')]
    words = filter(lambda word: word, words.split('\n'))
    for word in words:
        print'%s\t%s'%(word,1)
        
mapper实现--元组打印 (遇到空行实现不了)
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper_3_2.py
import sys
for line in sys.stdin:
    line = line.strip()
    if line.find('GET')!=-1:
        words=line[line.find('GET')+3:line.find('HTTP')]
    # if line.find('POST')!=-1:
    elif line.find('HEAD')!=-1:
        words=line[line.find('HEAD')+4:line.find('HTTP')]
    else:
        words=line[line.find('POST')+4:line.find('HTTP')]
    words = filter(lambda word: word, words.split('\n'))
    for word in words:
        print'%s\t%s'%(word,1)


reduce与之前一样


2.3 - 统计每个 ip,访问的子目录次数,输出如:175.44.30.93  /structure/heap/  8
取IP 和路径  1
如果一样 +1
思路:IP和目录用\t来做分隔符,然后使用特殊符号\@来做为和1的分隔符,在reduce中进行分割,然后比对IP和目录,进行累加
mapper实现
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper_3_3.py
import sys
for line in sys.stdin:
    line = line.strip()
    if line.find('GET')!=-1:
        words=line[:line.find(' ')]+'\t'+line[line.find('GET')+3:line.find('HTTP')]
    # if line.find('POST')!=-1:
    elif line.find('HEAD')!=-1:
        words=line[:line.find(' ')]+'\t'+line[line.find('HEAD')+4:line.find('HTTP')]
    elif line.find('POST')!=-1:
        words=line[:line.find(' ')]+'\t'+line[line.find('POST')+4:line.find('HTTP')]
    else:
        words='' 
    words = filter(lambda word:word, words.split('\n'))
    for word in words:
        print'%s\@%s'%(word,1)
        
reduce实现
#!/usr/bin/python
#_*_ coding:utf-8 _*_
#Filename:reduce.py


from operator import itemgetter
import sys


word2count = {}


for line in sys.stdin:
    line = line.strip()
    word,count = line.split('\@',1)
    try:
        count = int(count)
        word2count[word] = word2count.get(word,0)+count
    except ValueError:
        pass


sorted_word2count = sorted(word2count.items(),key=itemgetter(0))


for word,count in sorted_word2count:
    print'%s\t%s'%(word,count)
    


---------------------------------------------------------------------------------------------------------------------------------
3- mapreduce使用python  WordCount实例,使用python的迭代器和生成器改进mapper和reducer代码


mapper
#!/usr/bin/python
# _*_ coding:utf-8 _*_
#Filename:mapper_yield.py


import sys
def read_file(file):
        for line in file:
                yield line.split()


def main(separator='\t'):
    data=read_file(sys.stdin)
    for words in data:
        for word in words:
            print'%s%s%d'%(word,separator,1)


if __name__=='__main__':
        main()




reduce
#!/usr/bin/python
#_*_ coding:utf-8 _*_
#Filename:reduce_yield.py


from operator import itemgetter
import sys
from itertools import groupby


def read_file(file,separator):
    for  line in file:
        yield line.strip('').split(separator,1)


def main():
    separator='\t'
    data=read_file(sys.stdin,separator)
    word2count = {}
    for line in data:
#        print line
        word,count = line
        try:
            count = int(count)
            word2count[word] = word2count.get(word,0)+count
        except ValueError:
            pass
    sorted_word2count = sorted(word2count.items(),key=itemgetter(0))


    for word,count in sorted_word2count:
            print'%s%s%s'%(word,separator,count)
            
if __name__=='__main__':
    main()


-----------------------------------------------------------------------------------------------------------------------------------
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mapreduce python编程实例 的相关文章

  • 华为以太网链路聚合Eth-Trunk实验

    链路聚合Eth Trunk 什么是链路聚合 xff1f 原理基本术语聚合模式负载分担的逐流转发和逐包转发负载分担的延伸链路聚合实验一 手工聚合链路聚合实验二 LACP STATIC聚合链路聚合实验的疑问思考补充 xff0c 三层Eth Tr
  • 关于Linux 下的错误路由产生火星包的问题

    关于linux下的错误路由产生火星包的问题 错误原理 linux 下的route表 xff0c 不仅负责包的转发路径选择 xff0c 还负责检验包的来源的合理性 xff0c 比如 ip r default via 10 0 2 2 dev
  • 配置SSH的对等性

    在所有节点配置SSH的对等性 在安装Oracle Real Application clusters之前 必须先配置所有节点的SSH对等性 因为在安装过程种Oracle Universal Installer 使用ssh和scp命令执行远程
  • apt-get下载安装本地包

    一 使用场景 xff1a Ubuntu系统 1 Computer A不能上网 xff0c 需通过Computer B将安装包下载后 xff0c 拷贝给Computer A进行本地安装 前提是 xff0c 2台机器上的操作系统环境相同 2 也
  • sklearn专题六:聚类算法K-Means

    目录 1 概述 1 1 无监督学习与聚类算法 1 2 sklearn中的聚类算法 2 KMeans 2 1 KMeans是如何工作的 2 2 簇内误差平方和的定义和解惑 2 3 KMeans算法的时间复杂度 3 sklearn cluste
  • 查找某个导师(博导、硕导)所带学生的学位论文的步骤

    怎么查找某个导师 xff08 博导 硕导 xff09 所带学生的学位论文呢 xff1f 一般经过这几个步骤就能找到 xff1a 第一步 xff1a 在浏览器中输入网址https www cnki net xff0c 进入中国知网 第二步 x
  • 我的三色2016

    2016年于我来讲是无疑是迄今为止最为多彩与丰富的一年 xff0c 在这一年里我完成了从象牙塔到职场的过渡 xff0c 经历过迷茫 xff0c 遭受过歧视 xff0c 遇到过挑战 xff0c 好在上帝虽然关闭了所有的门却为我 打开了一道窗
  • 图像处理之Haar特征

    Haar like 特征是计算机视觉领域一种常用的特征描述算子 也称为 Haar 特征 xff0c 这是因为 Haar like 是受到一维 haar 小波的启示而发明的 所以称为类 Haar 特征 xff0c 后来又将 Haar like
  • 任意大小汉字点阵字库(字模)的制作与生成 单片机GUI/STemwin

    1 首先介绍一下汉字点阵在汉字库中的地址计算公式 xff1a 汉字库种类繁多 xff0c 但都是按照 区位的顺序 排列的 前一个字节为该汉字的区号 xff0c 后一个字节为该字的位号 每一个区记录94个汉字 xff0c 位号则为该字在该区中
  • ubuntu下ifconfig找不到命令,packege ‘net-tools‘ has no installation candidate

    PS xff1a 首先要将网络适配器设置为NAT模式 刚用虚拟机安装完ubuntu后 xff0c 实用ifconfig提示找不到命令 xff1a 用sudo apt install net tools也提示错误 xff1a Package
  • caffe+opencv linux安装

    有gpu http blog csdn net leijiezhang article details 53688157 仅CPU http blog csdn net u010402483 article details 51506616
  • Deep learning系列(十五)有监督和无监督训练

    1 前言 在学习深度学习的过程中 xff0c 主要参考了四份资料 xff1a 台湾大学的机器学习技法公开课 xff1b Andrew NG的深度学习教程 xff1b Li feifei的CNN教程 xff1b caffe官网的教程 xff1
  • c++ item

    C 43 43 书单 xff1a 1 第一本 基础好一些的 xff0c 可以看Stanley B Lippman的C 43 43 Primer xff0c 基础不太好的话 xff0c 可以看Stanley B Lippman的 Essent
  • 链表基础知识总结

    链表和数组作为算法中的两个基本数据结构 xff0c 在程序设计过程中经常用到 尽管两种结构都可以用来存储一系列的数据 xff0c 但又各有各的特点 数组的优势 xff0c 在于可以方便的遍历查找需要的数据 在查询数组指定位置 xff08 如
  • 关系型 和 非关系型 数据库使用场景

    面试 xff1a 你懂什么是分布式系统吗 xff1f Redis分布式锁都不会 xff1f gt gt gt 关系型数据库优点 SQL方便在多个表之间 做非常复杂的数据查询事务支持 安全性能高 关系型数据库缺点 不擅长大量数据的写入处理不擅
  • Dont't recreate the sequence! You would invalidate all independent objects and l

    原文出处 xff1a https community oracle com message 4016489 4016489 Dont 39 t recreate the sequence You would invalidate all i
  • June 11th 模拟赛C T1 Sandcas Solution

    空降题目处 点我点我点我 Description FJ居住的城堡有N个城墙 1 lt 61 N lt 61 25 000 xff0c 编号为1到N xff0c 每个城墙的高度为M i 1 lt 61 M i lt 61 100 000 xf
  • 树莓派3B安装64位系统

    树莓派是一款微型计算机 xff0c 并且树莓派3B是目前树莓派家族中唯一一款采用64位处理器的产品 但是树莓派官方提供的系统都是32位的 Linux操作系统厂商SUSE已经宣布专门为Raspberry Pi 3用户推出了一个64位Linux
  • winform中进行动态布局

    在某些网页中 xff0c 对有些按钮进行选择后 xff0c 网页中的布局会增加或者减少 xff0c 无论增加还是减少 xff0c 都会按照顺序进行排序 这个效果在winform中也是可以的 1 建立一个winform项目 2 拖动控件后 x
  • 【排坑】 Ubuntu 16.04 修改 lightdm.conf 后图形界面崩溃,报错 the system is running in low-graphics mode

    系统 Ubuntu 16 04 xff0c 英特尔最不值钱的复合显卡 起因 xff1a 笔者想要用 docker 的 container 能显示出一次些基础的视觉效果 xff0c 类似于在 container 中跑 matplot 函数 x

随机推荐