错误的MapReduce Mapper与Reducer代码排查及修正技术问询
MapReduce代码错误排查、修正与Reducer补全
嘿,我来帮你搞定这段MapReduce代码的问题,先排查Mapper的错误,再补全Reducer的逻辑:
Mapper代码错误排查与修正
原错误代码
#!/usr/bin/python import sys for line in sys.stdin: data = line.strip().split("\t") if len(data) == 6: date, time, place, temp, pressure, humidity = data print "{0}\t{1}".format(place, temp)
存在的问题
- 采用了Python2的
print语句语法,在Python3环境下会直接报错(Python3中print是函数,必须加括号) - 输出的
temp是字符串类型,后续Reducer做数值比较时会出现逻辑错误(比如字符串"9"会比"10"大)
修正后的代码
#!/usr/bin/python3 import sys for line in sys.stdin: data = line.strip().split("\t") if len(data) == 6: date, time, place, temp, pressure, humidity = data # 转换temp为浮点型,同时修正Python3的print函数语法 print("{0}\t{1}".format(place, float(temp)))
Reducer代码补全与修正
原未完成代码
#!/usr/bin/python import sys max_val = -sys.maxfloat oldKey = None for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: # Something has gone wrong. Skip this line. continue thisKey, thisVal = data_mapped if oldKey and oldKey != thisKey: print old...的内容
需要补全和修正的点
- 同样需要适配Python3的
print函数语法 - 必须将
thisVal转换为浮点型,否则字符串比较会得到错误结果 - 补全key切换时的输出逻辑,以及循环结束后处理最后一个key的逻辑
- 初始最大值用
float('-inf')比-sys.maxfloat更直观易懂
补全修正后的代码
#!/usr/bin/python3 import sys # 用负无穷作为初始最大值,更直观 max_val = float('-inf') oldKey = None for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: # 跳过格式错误的行 continue thisKey, thisVal = data_mapped try: # 尝试将温度值转换为浮点型,转换失败则跳过该行 thisVal = float(thisVal) except ValueError: continue if oldKey and oldKey != thisKey: # 当地点切换时,输出上一个地点的最高温度 print("{0}\t{1}".format(oldKey, max_val)) # 重置最大值和当前地点 max_val = thisVal oldKey = thisKey else: # 更新当前地点的最高温度 if thisVal > max_val: max_val = thisVal oldKey = thisKey # 循环结束后,输出最后一个地点的最高温度 if oldKey is not None: print("{0}\t{1}".format(oldKey, max_val))
内容的提问来源于stack exchange,提问作者jitender singh
相关产品推荐
相关产品推荐

