实验名称
求各年销售笔数,各年销售总额
实验目的
1、熟练理解和掌握MapReduce编程模型
2、掌握使用其他语言实现MapReduce
实验原理
http://hadoop.apache.org/docs/r1.0.4/cn/streaming.html
实验环境
Ubuntu 16.04
Hadoop 2.7.3
Python 3.6
实验要求
自行编写map.py代码,注意要点:
1、对空白行的处理,可判断 line[0] != ‘’
2、时间数据包含年月日,只需截取年份
3、可以将每行订单数据都算为1笔
4、目标输出格式:年份,数额
代码粘贴:
import sys
for line in sys.stdin:
if line[0]!="" :
col = line.strip().split(',')
col1=col[2].strip().split('-')
col[2]=col1[0]
print(col[2],',',col[6])
自行编写reduce.py代码,注意要点
1、可以将数据的行数当成笔数
2、输出时应按年份排好序
3、目标输出格式: 年份,笔数-总额
(总额要求转化成k且保留两位小数,如13572468.98 -> 13572.46k)
代码粘贴:
#!/bin/env python
# encoding: utf-8
from operator import itemgetter
import itertools
import sys
def read_mapper_output(file, separator = ','):
for line in file:
yield line.rstrip().split(separator,1)
stdin_generator=read_mapper_output(sys.stdin, ',')
for year, sals in itertools.groupby(stdin_generator,itemgetter(0) ):
count=0
total_sal=0
for year,cur_sal in sals:
count = count+1
total_sal=total_sal + float(cur_sal)
print(year,'\t',count,'\t','%.2f'%(total_sal/1000))
本地管道测试
cat sales.csv | python map.py | sort -k 1 | python reduce.py