python中MapReduce实战代码演示

python中MapReduce实战代码演示

使用pycharm编辑器,anaconda环境。
新建一个python.file,命名为map.py。具体代码如下

"""
wordcount单词统计
map阶段
"""
import sys
def map():
    for line in sys.stdin:  # 从标准输入里面读取的,是一个字符串格式
        words = line.split("\t")
        for word in words:
            print("\t".join([word.strip(), "1"]))


if __name__ == "__main__":
    map()

再新建一个python.file,命名为reduce.py。具体代码如下

'''
wordcount单词统计
reduce阶段
'''
import sys
from operator import itemgetter


def reduce():

    word_count_dict = {}  # 定义一个空字典
    for line in sys.stdin:  # for循环是为了计算每个单词最终出现的次数
        kv = line.split("\t") # 用split分割
        word = kv[0].strip()  # 为防止分割后有空格或者是换行符而采用strip,把字符串左右两边的空格去掉
        count = int(kv[1].strip()) # 使用int,把获取到的字符串类型转化为整型
        word_count_dict[word] = word_count_dict.get(word, 0) + count
        # 用该字典get方法,获取字典中存储的单词,若单词不存在,则返回值为0,再加上从标准输入获取到的值count

    sorted_word_count = sorted(word_count_dict.items(), key=itemgetter(0))

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


if __name__ == "__main__":
    reduce()

具体的代码逻辑解释,我写在备注上了,我也担心自己操作不熟练会忘记。

保存这两个文件,然后开始运行,建议将两个文件和你的要统计的txt文件放到同一个文件夹中。
例如我的:
在这里插入图片描述
其中we_test.txt文件内容如下,自己复制,自己保存到txt文件中:
hello world
hello python
hello java
hello hadoop
hello bigdata
hi python
hi mapreduce

具体操作如下:
win+r打开,输入cmd,运行,然后转到所在文件夹。打开时是默认路径,可以直接在后面输入
在这里插入图片描述
然后,输入dir,可以浏览该目录下的文件内容

在这里插入图片描述
然后使用type we_test.txt来查看we_test.txt文件的内容
在这里插入图片描述
然后通过type wc_test.txt|python map.py来运行map.py程序,运行结果如下
在这里插入图片描述
然后再通过type wc_test.txt|python map.py|sort对运行结果进行排序,结果如下
在这里插入图片描述
然后通过type wc_test.txt|python map.py|sort|python reduce.py来执行reduce.py程序,对已经统计出来的进行合计,结果如下。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44301621/article/details/89281098
今日推荐