wordcount程序

本文提供了一个简单的MapReduce实现示例,包括mapper和reducer函数。mapper函数负责将输入文本拆分为单词并计数,reducer函数汇总单词计数并输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import sys
def mapper(lines):
    maps=''
    lines.strip()
    lines=lines.split("\n")
    for line in lines:
        line.strip()
        words=line.split()
        for word in words:
            maps=maps+word+'\t1\n'
    return maps

def reducer(lines):
    wordCount={}
    lines.strip()    
    lines=lines.split("\n")
    lines=lines[0:len(lines)-2]
#    print lines
    for line in lines:
        line.strip()
        word,count=line.split('\t',1)
        try:
            count=int(count)
            wordCount[word]=wordCount.get(word,0)+count
        except ValueError:
            pass
    print wordCount.items()
    sorted_wordCount=sorted(wordCount.items(),key=lambda x:x[0])
    for word,count in sorted_wordCount:
        print("%s\t%s"%(word,count))
            

reducer(mapper("foo foo test show my mapp reduce quux labs\n"))
 代码很容易改造成mapreduce形式在hadoop上运行,如http://blog.youkuaiyun.com/yaoyepeng/article/details/5929457
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值