• 用Python写MapReduce函数——以WordCount为例


          尽管Hadoop框架是用java写的,但是Hadoop程序不限于java,可以用python、C++、ruby等。本例子中直接用python写一个MapReduce实例,而不是用Jython把python代码转化成jar文件。

          例子的目的是统计输入文件的单词的词频。

    • 输入:文本文件
    • 输出:文本(每行包括单词和单词的词频,两者之间用'\t'隔开)

    1. Python MapReduce 代码

          使用python写MapReduce的“诀窍”是利用Hadoop流的API,通过STDIN(标准输入)、STDOUT(标准输出)在Map函数和Reduce函数之间传递数据。

          我们唯一需要做的是利用Python的sys.stdin读取输入数据,并把我们的输出传送给sys.stdout。Hadoop流将会帮助我们处理别的任何事情。

    1.1 Map阶段:mapper.py

    在这里,我们假设把文件保存到hadoop-0.20.2/test/code/mapper.py

    1. #!/usr/bin/env python
    2. import sys
    3. for line in sys.stdin:
    4. line = line.strip()
    5. words = line.split()
    6. for word in words:
    7. print "%s\t%s" % (word, 1)

    文件从STDIN读取文件。把单词切开,并把单词和词频输出STDOUT。Map脚本不会计算单词的总数,而是输出 1。在我们的例子中,我们让随后的Reduce阶段做统计工作。

    为了是脚本可执行,增加mapper.py的可执行权限

    chmod +x hadoop-0.20.2/test/code/mapper.py

    1.2 Reduce阶段:reducer.py

    在这里,我们假设把文件保存到hadoop-0.20.2/test/code/reducer.py

    1. #!/usr/bin/env python
    2. from operator import itemgetter
    3. import sys
    4. current_word = None
    5. current_count = 0
    6. word = None
    7. for line in sys.stdin:
    8. line = line.strip()
    9. word, count = line.split('\t', 1)
    10. try:
    11. count = int(count)
    12. except ValueError: #count如果不是数字的话,直接忽略掉
    13. continue
    14. if current_word == word:
    15. current_count += count
    16. else:
    17. if current_word:
    18. print "%s\t%s" % (current_word, current_count)
    19. current_count = count
    20. current_word = word
    21. if word == current_word: #不要忘记最后的输出
    22. print "%s\t%s" % (current_word, current_count)

    文件会读取mapper.py 的结果作为reducer.py 的输入,并统计每个单词出现的总的次数,把最终的结果输出到STDOUT。

    为了是脚本可执行,增加reducer.py的可执行权限

    chmod +x hadoop-0.20.2/test/cod
  • 相关阅读:
    YUM退役了?DNF本地源配置
    嵌入式 程序调试之gdb和gdbserver的交叉编译及使用
    HR们,快看这是不是你想要的办公神器!
    Springboot 根据数据库表自动生成实体类和Mapper,只需三步
    玩转gRPC—不同编程语言间通信
    PID控制理论
    2024年阿里云创建【幻兽帕鲁/Palworld】32人联机服务器教程
    第二章《Java程序世界初探》第5节:算术运算符
    PS进阶篇——如何PS软件给图片部分位置打马赛克(四)
    双臂二指魔方机器人的制作(二)--视觉识别
  • 原文地址:https://blog.csdn.net/m0_72557783/article/details/128188483