用mapreduce 處理氣象數據集


用mapreduce 處理氣象數據集
編寫程序求每日最高最低氣溫,區間最高最低氣溫

氣象數據集下載地址為:ftp://ftp.ncdc.noaa.gov/pub/data/noaa

  • 按學號后三位下載不同年份月份的數據(例如201506110136號同學,就下載2013年以6開頭的數據,看具體數據情況稍有變通)
  • 解壓數據集,並保存在文本文件中
  • 對氣象數據格式進行解析
  • 編寫map函數,reduce函數
  • 將其權限作出相應修改
  • 本機上測試運行代碼
  • 放到HDFS上運行
  • 將之前爬取的文本文件上傳到hdfs上
  • 用Hadoop Streaming命令提交任務
  • 查看運行結果

本次的所有操作均在當前用戶目錄下的/temp/2018-05-09
通過wget下載壓縮文件,命令如下:

wget -drc --accept-regex=REGEX -P data ftp://ftp.ncdc.noaa.gov/pub/data/noaa/2015/6*

在這之前,需要配置好環境,在.bashrc中加入下面的命令

export PATH=$PATH:/usr/local/hbase/bin:/usr/local/hadoop/sbin:/usr/local/hadoop/bin
export HADOOP_HOME=/usr/local/hadoop
export STREAM=$HADOOP_HOME/share/hadoop/tools/lib/hadoop-streaming-*.jar

下載后解壓,之后啟動hdfs,將解壓文件放入系統中,命令如下

start-dfs.sh
hdfs dfs -mkdir weather_data 
hdfs dfs -put weather.txt weather_data/

文件放入系統后可以編寫mapper.py了,主要代碼如下:

import sys

for line in sys.stdin:
    line = line.strip()
    print('%s\t%d' % (line[15:23], int(line[87:92])))

reducer.py了,主要代碼如下:

from operator import itemgetter
import sys

current_date = None
current_temperature = 0
date = None

for line in sys.stdin:
    line = line.strip()
    date, temperature = line.split('\t', 1)
    try:
        temperature = int(temperature)
    except ValueError:
        continue

    if current_date == date:
        if current_temperature < temperature:
            current_temperature = temperature
    else:
        if current_date:
            print('%s\t%d' % (current_date, current_temperature))
        current_temperature = temperature
        current_date = date

if current_date == date:
    print('%s\t%d' % (current_date, current_temperature))

上面的reducer是求出最高氣溫,求出最低只需要將
if current_temperature < temperature:改為 if current_temperature > temperature:

這里測試運行mapper和reducer,命令如下:

chmod a+x mapper.py 
chmod a+x reducer.py 
cat test.txt | python mapper.py | python reducer.py 

test.txt中包含了部分的天氣數據
下面是運行截圖:
enter description here

運行成功后可編寫run.sh


hadoop jar $STREAM \
-D stream.non.zero.exit.is.failure=false \
-file /home/hadoop/temp/2018-05-09/mapper.py \
-mapper 'python /home/hadoop/temp/2018-05-09/mapper.py' \
-file /home/hadoop/temp/2018-05-09/reducer.py \
-reducer 'python /home/hadoop/temp/2018-05-09/reducer.py' \
-input /user/hadoop/weather_data/*.txt \
-output /user/hadoop/weather_output

運行run.sh

source run.sh

最后的運行結果通過cat打印截圖:
enter description here

/temp下的文件在鏈接中下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM