python在hadoop上运行

来源:互联网 发布:c语言接口 编辑:程序博客网 时间:2024/04/30 13:52

1、命令样式:

        

  1. hadoop jar $STREAM \
  2. -files ./mapper.py,./reducer.py \
  3. -mapper ./mapper.py \
  4. -reducer ./reducer.py \
  5. -input /user/$(whoami)/input/*.txt \
  6. -output /user/$(whoami)/output
  1. hadoop jar share/hadoop/tools/lib/hadoop-streaming-2.7.2.jar -files source/map_temperature.py,source/reduce_temperature.py -mapper map_temperature.py -reducer reduce_temperature.py -input /input/temperature1/* -output /output/MaxTemp4

2、本地测试方法:

  1. cat 1901.txt | python map_temperature.py | sort | python reduce_temperature.py

3、源码

mapper.py

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import re
  4. import sys
  5. for line in sys.stdin:
  6.    val = line.strip()
  7.    try:
  8.        (year, temp, q) = (val[15:19],val[87:92],val[92:93])
  9.    except:
  10.        (year, temp, q) = (2014,25,1)
  11.    # print ("{},{},{}".format(year,temp,q))
  12.    if temp!= "+9999" and re.match("[01459]",q):
  13.        print "%s,%s"%(year,temp)

recudce.py

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import sys
  4. (last_key, max_val) = (None, -sys.maxint)
  5. for line in sys.stdin:
  6.    # print line
  7.    # print line.strip().split(",")
  8.    try:
  9.        (key, val) = line.strip().split(",")
  10.        if last_key and last_key!= key:
  11.            print "%s,%s"%(last_key,max_val)
  12.            (last_key, max_val) = (key, int(val))
  13.        else:
  14.            (last_key, max_val) = (key, max(max_val, int(val)))
  15.    except:
  16.        print "==================error=========================="
  17.        continue
  18. if last_key:
  19.    print "%s,%s"%(last_key, max_val)
0 0