파이썬

실시간 미세먼지농도 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
“무릇 물이란 지세를 따라 흐르되 작은 틈도 놓치지 않고 적시니 지혜를 갖춘 자와 같고, 움직이면서 아래로 흘러가니 예를 갖춘 자와 같으며, 어떤 깊은 곳도 머뭇거리지 않고 들어가니 용기를 가진 자와 같고 장애물이 막혀서 갇히면 고요히 맑아지니 천명을 아는 자와 같으며, 험한 곳을 거쳐 멀리 흐르지만 끝내 남을 허물어뜨리는 법이 없으니 덕을 가진 자와 같다. 천지는 이것으로 이루어지고, 만물은 이것으로 살아가며, 나라는 이것으로 안녕을 얻고, 만사는 이것으로 평안해지며, 만물은 이것으로 바르게 되는 것이다. 이것이 지혜로운 자가 물을 좋아하는 이유이다.” (한영, <<한시외전>>)