Assignment2
主要就是扔到DataFrame里,其他的就能顺带着解决了
这几天学学html,过两天重新学学写爬虫(闲)
# -*- coding: utf-8 -*-
"""
Spyder Editor
IC2140/TM3300
TMA Template for Exercise 3
"""
import requests
import pandas as pd
import json
import sys, getopt
dUpdate=""
weather=pd.DataFrame({'A' : []})
#%%
def getData():
global dUpdate,weather
url="https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=rhrread&lang=en"
response = requests.get(url)
data = response.text
jdata = json.loads(data)
dTemp=jdata['temperature']['data']
dRain=jdata['rainfall']['data']
dUpdate=jdata['updateTime']
dfTemp=pd.DataFrame(dTemp)
dfRain=pd.DataFrame(dRain)
### Your code
### Q1
###
weather=pd.merge(dfTemp,dfRain,on='place',how='outer')
weather=weather.set_index(weather['place'])
weather=weather.drop(columns='place')
weather=weather.sort_index()
weather=weather[['unit_y','max','main','value','unit_x']]
#%%
def getDateTime(sDateTime):
sDate=sDateTime.split("T")[0]
sTime=sDateTime.split("T")[1].split("+")[0]
return sDate,sTime
#%%
def getTempRain(Region,weather):
nTemp=-1
nRain=-1
### Your Code
### Q2
###
tmp1=weather.loc[Region,'value']
if not(pd.isnull(tmp1)):
nTemp=tmp1
tmp2=weather.loc[Region,'main']
if tmp2!='FALSE' and (not(pd.isnull(tmp2))):
nRain=tmp2
return nTemp,nRain
#%%
def Report(Place,cTemp, cRain,cDate,cTime):
if cTemp==-1 and cRain==-1:
print('No record for {}'.format(Place))
return
print("-----------------------------------------------")
print("Current Weather Summary on {} at {}".format(cDate,cTime))
print("Location: {}".format(Place))
### Your code
### Q3
###
if cTemp!=-1: print("Current Temperature: {:.1f} C".format(cTemp))
if cRain!=-1:
if cRain<0.05: print('No rainfall for the last hour')
else: print("Rainfall for the last hour: {:.1f} mm".format(cRain))
print("----------------End of Report-----------------")
#%%
mHELP = 'weather.py -r Region'
def main(argv):
try:
opts, args = getopt.getopt(argv,"r:")
except getopt.GetoptError:
print (mHELP)
sys.exit(2)
for opt, arg in opts:
if opt == '-r':
sDate,sTime=getDateTime(dUpdate)
nTemp,nRain=getTempRain(arg,weather)
### Your Code
### Q4
###
Report(arg,nTemp,nRain,sDate,sTime)
sys.exit()
print(mHELP)
# LastReport()
if (__name__ == "__main__"):
getData()
main(sys.argv[1:])
else:
## Unit Test for Q1, Q2 and Q3
print("Testing")
getData()