파이썬

실시간 미세먼지농도 Open Api 자료 받아와 저장하기, 받아온 자료 그래프로 그리기

컨텐츠 정보

본문

텍스트 파일로 자료 저장하기.

=======================

# -*- coding: cp949 -*-

import urllib2

import os

import time as tm

import numpy as np

import matplotlib.dates as date

import datetime

import sys

 

gap=input("몇초 동안의 자료를 수집할까요?")

lines=np.empty((gap,3))

 

for i in range(0,gap):

    url="http://openapi.seoul.go.kr:8088/****/json/ListAvgOfSeoulAirQualityService/1/5";

    data=urllib2.urlopen(url).read();

    stp=data.find("PM10")+6;

    edp=data.find("PM25")-2;

    asctime=str(tm.asctime())

    asctime=asctime[4:24]

    if asctime[0:3]=='Sep':

        asctime=asctime.replace('Sep','9')

        

    asctime=asctime.replace(':','')

    asctime=asctime.replace(' ','')

    asctime=int(asctime)

    lines[i][0]=asctime

    lines[i][1]=tm.time()

    lines[i][2]=float(data[stp:edp])

    loading=gap-i

    print loading

    tm.sleep(1)

            

dts=map(datetime.datetime.fromtimestamp,lines[:,1])

fds=date.date2num(dts)

lines[:,1]=fds

filename0=str(lines[0][0])

filename0=filename0.replace('.','')

filename0=filename0[:9]

filename1=str(lines[gap-1][0])

filename1=filename1.replace('.','')

filename1=filename1[:9]

nlocaltime=str(tm.localtime())

ystp=nlocaltime.find('tm_year')+8

yedp=ystp+4

nyear=str(nlocaltime[ystp:yedp])

mstp=nlocaltime.find('tm_mon')+7

medp=nlocaltime.find(', tm_mday')

nmon=str(nlocaltime[mstp:medp])

dstp=nlocaltime.find('tm_mday')+8

dedp=nlocaltime.find(', tm_hour')

nday=str(nlocaltime[dstp:dedp])

 

if os.path.exists(nyear+nmon+nday):

    os.chdir(nyear+nmon+nday)

else:

    os.mkdir(nyear+nmon+nday);

    os.chdir(nyear+nmon+nday)

np.savetxt(filename0+' to '+filename1+'.txt',lines,header='asctime(m,d,h,m,s,y),date2num,pm10(microgram/cubic meter)')

os.chdir(os.path.dirname(os.getcwd()))

print filename0+' to '+filename1+'.txt 로 저장되었습니다.'

 

========================= 

텍스트 파일로 자료 저장하기 끝.

=========================

자료를 바탕으로 그래프 그리기.

=========================

# -*- coding: cp949 -*-

import os

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.dates as date

import glob as gb

 

getdate=str(input("원하는 자료의 년도,월,일 을 기호 없이 입력해 주십시오."))

os.chdir(getdate)

filelist=gb.glob('*.txt')

hfmt = date.DateFormatter('%m/%d %H:%M:%S')

 

 

for i in range(0,len(filelist)):

    check=raw_input(filelist[i]+"을 그릴 까요?(y/n)")

    if check == 'y':

        numtime,pm10=np.loadtxt(filelist[i],unpack=True,skiprows=1,usecols=[1,2])

        fig=plt.figure(i)

        ax=fig.add_subplot(111)

        ax.xaxis.set_major_locator(date.AutoDateLocator())

        ax.xaxis.set_major_formatter(hfmt)

        plt.plot(numtime,pm10)

        plt.xticks(rotation='vertical')

        plt.subplots_adjust(bottom=.3)

        plt.xlabel('Time')

        plt.ylabel('$\mu$g/m^3')

        plt.title(filelist[i])

        figname=filelist[i]

        figname=figname[:-4]

        if os.path.exists('fig'):

            os.chdir('fig')

        else:

            os.mkdir('fig');

            os.chdir('fig')

        plt.savefig(figname+".png")

        os.chdir(os.path.dirname(os.getcwd()))

        print figname+'.png 로 저장되었습니다.'

    else:

        pass

 

 

 

관련자료

댓글 0
등록된 댓글이 없습니다.
Today's proverb
유쾌한 사람은 자기 일에만 몰두하는 사람이 아니다. 때론 자신의 일을 전부 제쳐놓고 타인의 문제에 전력을 쏟는 열정이 있는 사람이다. 타인에게 자신의 힘을 나누어주고 마음을 열어주는 것은 자신의 삶을 행복하게 만드는 방법이다.