Python中的MapReduce以及在Hadoop环境下运行之词频统计
一、在Linux中运行
首先在Linux中新建下面的目录,里面什么也不要放,然后进入到目录 /opt/data/mapreduce_test/
1. 然后在里面创建一个test.txt文件,并往里面添加一些需要统计的单词,
2. 接着编辑mapper.py文件,vim mapper.py
1 2 3 4 5 6 7 8 | #!/usr/bin/env python # encoding=utf-8 import sys for line in sys.stdin: line = line.strip() words = line.split() for word in words: print ( "%s\t%s" % (word, 1 )) |
3. 接着新建reduce.py文件, vim reduce.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #!/usr/bin/env python # encoding=utf-8 from operator import itemgetter import sys current_word = None current_count = 0 word = None for line in sys.stdin: line = line.strip() word, count = line.split( '\t' , 1 ) try : count = int (count) except ValueError: #count如果不是数字的话,直接忽略掉 continue 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 word = = current_word: #不要忘记最后的输出 print ( "%s\t%s" % (current_word, current_count)) |
4.分别对mapper.py和reduce.py 授权
1 2 3 | [root@master mapreduce_test] # chmod -R 777 mapper.py [root@master mapreduce_test] # chmod -R 777 reduce.py [root@master mapreduce_test] # chmod -R 777 test.txt |
5. 接下来开始运行mapper.py程序运行,
1 | more test.txt | python . / mapper.py |
排序运行
1 | more test.txt | python . / mapper.py | sort |
1 | more test.txt | python . / mapper.py | sort - k1, 1 |
6. mapper和reduce同时运行
1 | more test.txt | python . / mapper.py | sort - k1, 1 | . / reduce .py |
二、在Hadoop环境中运行
还是在这个目录下,新建一个run.sh文件
里面的内容如下:
1 2 3 4 | hadoop jar / opt / soft / hadoop - 2.7 . 7 / share / hadoop / tools / lib / hadoop - streaming - 2.7 . 7.jar \ - file / opt / data / mapreduce_test / mapper.py - mapper / opt / data / mapreduce_test / mapper.py \ - file / opt / data / mapreduce_test / reduce .py - reducer / opt / data / mapreduce_test / reduce .py \ - input / tmp / py / input / * - output / tmp / py / output |
第一行配置的是hadoop-streaming-2.7.5.jar所在的位置
然后给run.sh添加可执行权限
接着在hdfs环境下新建文件夹,
1 | hdfs dfs - mkdir - p / tmp / py / input |
然后把test.txt上传进去
1 | hdfs dfs - put test.txt / tmp / py / input |
接着运行run.sh
1 | source run.sh |
接着查看生成的文件
1 | hdfs dfs - ls / tmp / py / output |
其中part-00000就是运行结果,打开看一下
1 | hdfs dfs - cat / tmp / py / output / part - 00000 |
然后把运行结果保存到本地
1 | hdfs dfs - get / tmp / py / output / part - 00000 / opt / data |
本文参考:Python中的MapReduce以及在Hadoop环境下运行_秦哥的博客-CSDN博客
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏