使用python实现Hadoop中MapReduce

Hadoop包含HDFS(分布式文件系统)、YARN(资源管理器)、MapReduce(编程模型)。
一、MapReduce的编程原理
MapReduce 是一种编程模式,用于大规模的数据集的分布式运算。通俗的将就是会将任务分给不同的机器做完,然后在收集汇总。
map阶段(分解):单独计算任务,每个机器尽量计算自己hdfs内部的保存信息(即复杂问题分解成多个简单任务,并数据分块存储)
reduce阶段(合并):多个任务并行,将map的输出结果作为输入合并求解。
使用python写MapReduce是利用HadoopStreaming的API,通过STDIN(标准输入)、STDOUT(标准输出)在Map函数和Reduce函数之间传递数据。
二、程序
(1)map阶段

import sys
def map():
    #标准输入读取的数据每一行是字符串格式,可以使用split进行分割
    for line in sys.stdin:
        words = line.split(" ")
        for word in  words:
            #单词作为key,1作为value
            print("\t".join([word.strip(),"1"]))`

(2)reduce阶段

import sys
from operator import itemgetter
def reduce():
    word_count_dict = {
    
    }
    for line in sys.stdin:
        kv = line.split("\t")
        word = kv[0].strip()
        count = int(kv[1].strip())
        #使用字典类型数据get(key,default)方法,统计单词个数,如没有默认填写0,如果有在原有的基础上累加
        word_count_dict[word] = word_count_dict.get(word,0)+count
    #将统计的数据按照key值(即word)的首字母进行排序
    sorted_word_count = sorted(word_count_dict.items(),key = itemgetter(0))

    for word ,count in sorted_word_count:
        print("\t".join([word.str(count)]))

(3)运行(windows系统)
1)首先使用命令(type 文档名称)查看txt文档
打开cmd命令提示符,到文档存储路径下,输入type word.txt(word.txt是要查看的文档),如图所示:
在这里插入图片描述
2)使用命令执行map程序
按照程序执行顺序展示结果:type word.txt | python map.py
按照程序执行,并将执行结果按照字母顺序进行排序:type word.txt | python map.py |sort
在这里插入图片描述
3)执行reduce程序
type word.txt | python map.py |sort |python reduce.py
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44801116/article/details/109828349