前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用python解释mapreduce

用python解释mapreduce

作者头像
零月
发布2018-04-25 16:17:05
6740
发布2018-04-25 16:17:05
举报
文章被收录于专栏:从零开始的linux从零开始的linux
map
代码语言:javascript
复制
import sys

#输入为标准输出stdin
for line in sys.stdin:
    #删除开头和结尾的空行
    line = line.strip()
    #以默认空格分隔单词到words列表
    words = line.split()
    for word in words:
        #输出所有单词,格式为“单词,1”以便为reduce的输入
        print '%s %s' % (word,1)
reduce
代码语言:javascript
复制
import sys
current_word = None
current_count = 0
word = None

#获取标准输入,即map.py的标准输出
for line in sys.stdin:
    #删除开头和结尾的空行
    line = line.strip()

    #解析map.py输出作为程序的输入,以tab作为分隔符
    word,count = line.split( )
    #转换count从字符型到整型
    try:
        count = int(count)
    except ValueError:
        #count非数字时,忽略此行
        continue

    #要求map.py的输出做排序(sort)操作,以便对连续的word做判断
    if current_word == word:
        current_count += count
    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)

文本

代码语言:javascript
复制
foo foo puu labs foo puu abc bar see you by test test
abc labs foo me python hadoop ab ac ab bc bc python

运行

代码语言:javascript
复制
[root@alex ~]# cat ce.txt | python map.py | sort | python reduce.py 
ab     2
abc    2
ac     1
bar    1
bc     2
by     1
foo    4
hadoop   1
labs   2
me     1
puu    2
python  2
see    1
test   2
you    1
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-02-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 从零开始的linux 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • map
  • reduce
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档