美文网首页Mac优雅使用指南
开发天气情况采集程序

开发天气情况采集程序

作者: 不正经运维 | 来源:发表于2018-09-20 10:35 被阅读5次

    开发天气情况采集程序

    天气情况采集程序

    每天都要记录时间日志,从最初的九宫格到目前的 UniLog ,已经经历了好多个版本。其中天气的情况记录十分有用,但是获取天气的信息是个比较麻烦的事情,作为一个 IT 工作者,怎能被这种问题所耽搁?

    背景

    每天都要记录时间日志,从最初的九宫格到目前的 UniLog ,已经经历了好多个版本。

    九宫格中的天气情况我觉得很有用,有时候都可以借此回顾当天的具体情形。

    这样的好天气,怎么能没有你?

    ——韦礼安《好天气》

    自然,在 UniLog 中,也继承了天气的填写,信息更全:

    ⛅,26 ~ 32℃,🌪东北风3-4级,💧97%,🌱32

    是不是看起来很不错?

    但是处理很费时间,打开网页或手机,到处找这些信息……

    一个搞 IT 的怎么能让这种问题难倒?

    需求

    写个脚本什么的,一键复制就好了。

    分析

    数据源

    自然是天气预报了,仔细看了下,墨迹天气会比较好些。具体用网页还是API呢?默认API,为什么我就不说了,感觉API会比较稳定些。

    阿里云市场中有墨迹的API提供,使用免费版本即可:

    https://market.aliyun.com/products/57096001/cmapi023656.html

    对应接口主要有:

    • 精简预报3天;全天预报,比较稳定,但是没有湿度和AQI信息;
    • 精简预报实况:实时信息;
    • 精简AQI:只有空气质量信息;

    从不同的API取对应的信息即可,好烦……☹️

    数据处理

    获取了数据,就很好办了:

    1. 处理原始文本,替换图标或者增加图标;
    2. 拼接成最终结果;

    其他

    有几个额外的需求:

    1. 没空看结果如何,所以最好语音提示,用say命令就好了;
    2. 保存到剪贴板中;
    3. 不要给我弹出对话框:那就用Automator来生成app就好了。

    解决方案

    代码放在了Github中:getWeather

    将下述内容保存为`getMojiWeather.py'

    #!/bin/env python
    # -*- coding=utf-8 -*-
    
    __author__ = u'Rex Kang'
    __description__ = u'根据需求,调用墨迹API生成一句话简介。'
    __license__ = u'GPL - http://www.fsf.org/licenses/gpl.txt';
    __history__ = {
        u'1.0': [u'2017/05/19', u'调用墨迹API,完成基本功能'],
        u'1.1': [u'2017/06/08', u'调用墨迹API,完成基本功能']
    }
    import urllib, urllib2, sys, json
    
    
    def mojiAPI(apiDict, cityID, appCode):
        method = 'POST'
        querys = ''
        bodys = {}
        url = apiDict['host'] + apiDict['path']
    
        # CityID来自于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)
        # 根据API的要求,定义相对应的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'精简预报3天',
                'host': 'http://freecityid.market.alicloudapi.com',
                'path': '/whapi/json/alicityweather/briefforecast3days',
                'token': '677282c2f1b3d718152c4e25ed434bc4'
            },
            'BriefCondition': {
                'name': u'精简预报实况',
                'host': 'http://freecityid.market.alicloudapi.com',
                'path': '/whapi/json/alicityweather/briefcondition',
                'token': '46e13b7aab9bb77ee3358c3b672a2ae4'
            },
            'AQI': {
                'name': u'精简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级,湿度%s%%,%s%s' % tuple(strList)
            print str.encode('utf-8')
    

    将下述内容在 Automator保存为getWeather.app

    cd ScriptDir
    python MojiWeatherFromAPI.py
    [ $? -eq 0 ] && say 'Weather copied.' && exit
    say 'Error occurred.' && exit 1
    

    其他

    CityID

    CityID可以用下述方式获取,将海口换成对应的城市:

    1. 访问链接地址:http://tianqi.moji.com/api/citysearch/海口
    2. 第一个cityid就是了,海口为1020

    相关文章

      网友评论

        本文标题:开发天气情况采集程序

        本文链接:https://www.haomeiwen.com/subject/hiygnftx.html