-1

我一直在为我的 Skype Bot 使用 Skype4Py。
我想知道如何订购 API 响应的内容。
例如,如果我想获取天气,我会输入 !weather
,它会响应:

收集天气信息。请稍候......
天气:{“数据”:{“current_condition”:[{“cloudcover”:“0”,“湿度”:“39”,“observation_time”:“11:33 AM”,“precipMM”: “0.0”,“压力”:“1023”,“temp_C”:“11”,“temp_F”:“51”,“能见度”:“16”,“weatherCode”:“113”,“weatherDesc”:[{ “值”:“清除”}],“weatherIconUrl”:[{“值”:“http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png”}],“winddir16Point”:“N”, “winddirDegree”:“0”,“windspeedKmph”:“0”,“

我想让它更像:

天气:
当前温度:51 F | 22 C
湿度:39%
风速:0 MPH

或者像这样干净利落的东西。
这样它在 Skype 中看起来不那么难看,而且看起来更专业。


我应该添加代码:

    def weather(zip):
try:
    return urllib2.urlopen('http://api.worldweatheronline.com/free/v1/weather.ashx?q='+zip+'&format=json&num_of_days=1&fx=no&cc=yes&key=r8nkqkdsrgskdqa9spp8s4hx' ).read()
except:
    return False

那是我的functions.py

这是我的commands.py:

                        elif msg.startswith('!weather '):
                    debug.action('!weather command executed.')
                    send(self.nick + 'Gathering weather information. Please wait...')
                    zip = msg.replace('!weather ', '', 1);
                    current = functions.weather(zip)
                    if 4 > 2:
                        send('Weather: ' + current)
                    else:
                        send('Weather: ' + current)

就像我说的,我正在使用 Skype4Py,是的。

4

1 回答 1

0

您的 API 正在返回json,您需要对其进行解析:

import requests

url = 'http://api.worldweatheronline.com/free/v1/weather.ashx'
params = {'format': 'json',
          'num_of_days': 1, 'fx': 'no', 'cc': 'yes', 'key': 'sekret'}
params['zip'] = 90210

r = requests.get(url, params=params)
if r.status_code == 200:
   results = r.json()

print('Weather:
Current Temp: {0[temp_f]} F | {0[temp_c]} C
Humidity: {0[humidity]}%
Wind Speed: {0[windspeedMiles]} MPH'.format(results[0]))

我正在使用优秀的requests图书馆

于 2013-12-15T12:23:53.527 回答