開(kāi)發(fā)天氣情況采集程序
每天都要記錄時(shí)間日志使碾,從最初的九宮格到目前的 UniLog 底洗,已經(jīng)經(jīng)歷了好多個(gè)版本。其中天氣的情況記錄十分有用,但是獲取天氣的信息是個(gè)比較麻煩的事情腾么,作為一個(gè) IT 工作者奈梳,怎能被這種問(wèn)題所耽擱?
背景
每天都要記錄時(shí)間日志解虱,從最初的九宮格到目前的 UniLog 攘须,已經(jīng)經(jīng)歷了好多個(gè)版本。
九宮格中的天氣情況我覺(jué)得很有用殴泰,有時(shí)候都可以借此回顧當(dāng)天的具體情形于宙。
這樣的好天氣,怎么能沒(méi)有你悍汛?
——韋禮安《好天氣》
自然捞魁,在 UniLog 中,也繼承了天氣的填寫(xiě)离咐,信息更全:
?谱俭,26 ~ 32℃,??東北風(fēng)3-4級(jí)宵蛀,??97%昆著,??32
是不是看起來(lái)很不錯(cuò)?
但是處理很費(fèi)時(shí)間术陶,打開(kāi)網(wǎng)頁(yè)或手機(jī)凑懂,到處找這些信息……
一個(gè)搞 IT 的怎么能讓這種問(wèn)題難倒?
需求
寫(xiě)個(gè)腳本什么的瞳别,一鍵復(fù)制就好了征候。
分析
數(shù)據(jù)源
自然是天氣預(yù)報(bào)了,仔細(xì)看了下祟敛,墨跡天氣會(huì)比較好些疤坝。具體用網(wǎng)頁(yè)還是API
呢?默認(rèn)API
馆铁,為什么我就不說(shuō)了跑揉,感覺(jué)API
會(huì)比較穩(wěn)定些。
阿里云市場(chǎng)中有墨跡的API
提供埠巨,使用免費(fèi)版本即可:
https://market.aliyun.com/products/57096001/cmapi023656.html
對(duì)應(yīng)接口主要有:
- 精簡(jiǎn)預(yù)報(bào)3天历谍;全天預(yù)報(bào),比較穩(wěn)定辣垒,但是沒(méi)有濕度和
AQI
信息望侈; - 精簡(jiǎn)預(yù)報(bào)實(shí)況:實(shí)時(shí)信息;
- 精簡(jiǎn)AQI:只有空氣質(zhì)量信息勋桶;
從不同的API
取對(duì)應(yīng)的信息即可脱衙,好煩……??
數(shù)據(jù)處理
獲取了數(shù)據(jù)侥猬,就很好辦了:
- 處理原始文本,替換圖標(biāo)或者增加圖標(biāo)捐韩;
- 拼接成最終結(jié)果退唠;
其他
有幾個(gè)額外的需求:
- 沒(méi)空看結(jié)果如何,所以最好語(yǔ)音提示荤胁,用
say
命令就好了瞧预; - 保存到剪貼板中;
- 不要給我彈出對(duì)話框:那就用
Automator
來(lái)生成app
就好了仅政。
解決方案
代碼放在了Github中:getWeather垢油。
將下述內(nèi)容保存為`getMojiWeather.py'
#!/bin/env python
# -*- coding=utf-8 -*-
__author__ = u'Rex Kang'
__description__ = u'根據(jù)需求,調(diào)用墨跡API生成一句話簡(jiǎn)介已旧。'
__license__ = u'GPL - http://www.fsf.org/licenses/gpl.txt';
__history__ = {
u'1.0': [u'2017/05/19', u'調(diào)用墨跡API秸苗,完成基本功能'],
u'1.1': [u'2017/06/08', u'調(diào)用墨跡API,完成基本功能']
}
import urllib, urllib2, sys, json
def mojiAPI(apiDict, cityID, appCode):
method = 'POST'
querys = ''
bodys = {}
url = apiDict['host'] + apiDict['path']
# CityID來(lái)自于https://github.com/IceblueSakura/GetWeather/blob/master/Cityid.xml
bodys['cityId'] = cityID
bodys['token'] = apiDict['token']
post_data = urllib.urlencode(bodys)
request = urllib2.Request(url, post_data)
request.add_header('Authorization', 'APPCODE ' + appCode)
# 根據(jù)API的要求运褪,定義相對(duì)應(yīng)的Content-Type
request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
response = urllib2.urlopen(request)
content = response.read()
if (content):
contentDict = {}
try:
contentDict = json.loads(content)
except Exception, err:
pass
finally:
return contentDict
def getCityID(city=u'壕ィ口市'):
cities = {
u'海口市': '1020',
u'三亞市': '1022',
u'烏魯木齊市': '2505',
u'西安市': '2182',
}
return cities.get(city, '航斩铮口市')
# v1.1 Modified Start
def getWetaherIcon(w=u'晴'):
weatherIcon = {
u'晴': u'??',
u'陰': u'??',
u'多云': u'?',
u'陣雨': u'??',
u'雨': u'??',
u'中雨': u'?',
}
return weatherIcon.get(w, '??')
def getAOIIcon(aqi=40):
icon = u'??'
if int(aqi) > 150:
icon = u'??'
elif int(aqi) > 75:
icon = u'??'
return icon
# v1.1 Modified end
def main():
API = {
'BriefForecast': {
'name': u'精簡(jiǎn)預(yù)報(bào)3天',
'host': 'http://freecityid.market.alicloudapi.com',
'path': '/whapi/json/alicityweather/briefforecast3days',
'token': '677282c2f1b3d718152c4e25ed434bc4'
},
'BriefCondition': {
'name': u'精簡(jiǎn)預(yù)報(bào)實(shí)況',
'host': 'http://freecityid.market.alicloudapi.com',
'path': '/whapi/json/alicityweather/briefcondition',
'token': '46e13b7aab9bb77ee3358c3b672a2ae4'
},
'AQI': {
'name': u'精簡(jiǎn)AQI',
'host': 'http://freecityid.market.alicloudapi.com',
'path': '/whapi/json/alicityweather/briefaqi',
'token': '4dc41ae4c14189b47b2dc00c85b9d124'
}
}
city = u'YourCity'
appCode = 'YourAppCode'
resultOfCondition = mojiAPI(API['BriefCondition'], getCityID(city), appCode)
resultOfForecast = mojiAPI(API['BriefForecast'], getCityID(city), appCode)
resultOfAQI = mojiAPI(API['AQI'], getCityID(city), appCode)
strList = ['']*8
try:
if resultOfCondition and 'data' in resultOfCondition:
cond = resultOfCondition['data']['condition']
strList[0] = getWetaherIcon(cond['condition']) # v1.1 Modified
strList[5] = cond['humidity']
if resultOfForecast and 'data' in resultOfForecast:
fore = resultOfForecast['data']['forecast'][1]
strList[1] = fore['tempNight']
strList[2] = fore['tempDay']
strList[3] = fore['windDirDay']
strList[4] = fore['windLevelDay']
if resultOfAQI and 'data' in resultOfAQI:
strList[7] = resultOfAQI['data']['aqi']['value']
strList[6] = getAOIIcon(strList[7]) # v1.1 Modified
except Exception, err:
print Exception,err
finally:
str = u'%s檀咙,%s ~ %s℃,%s%s級(jí)璃诀,濕度%s%%弧可,%s%s' % tuple(strList)
print str.encode('utf-8')
將下述內(nèi)容在 Automator保存為getWeather.app
:
cd ScriptDir
python MojiWeatherFromAPI.py
[ $? -eq 0 ] && say 'Weather copied.' && exit
say 'Error occurred.' && exit 1
其他
CityID
CityID
可以用下述方式獲取,將毫踊叮口換成對(duì)應(yīng)的城市:
- 訪問(wèn)鏈接地址:http://tianqi.moji.com/api/citysearch/鹤厮校口;
- 第一個(gè)
cityid
就是了凿将,盒L祝口為1020
。