标签:
最近犯懒,但这么长时间没点成果实在过意不去。朋友研究树莓派,前几天帮他写个语音天气预报的程序。就让我用来凑个数吧。
#coding=utf-8
import urllib2,json,subprocess,time
‘‘‘使用云聚数据的接口获取天气数据,接口文档:
实时天气接口:http://www.36wu.com/Service/Details/1
生活气象指数:http://www.36wu.com/Service/Details/1?cid=5
需要安装espeak
‘‘‘
def get_weather_data():
header = {‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘}
req = urllib2.Request(url=‘http://api.36wu.com/Weather/GetWeatherIndex?district=%E5%8C%97%E4%BA%AC&format=json‘,headers=header)
weather = json.loads(urllib2.urlopen(req).read())
req = urllib2.Request(url=‘http://api.36wu.com/Weather/GetWeather?district=%E5%8C%97%E4%BA%AC&format=json‘,headers=header)
weather[‘data‘].update(json.loads(urllib2.urlopen(req).read())[‘data‘])
return weather
def tts_head():
fd = subprocess.Popen([‘espeak‘,‘-vzh‘],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)#为了不让它输出任何东西:)
def sayn(str):
fd.stdin.write(‘\n‘)
fd.stdin.write(str)
#犯懒:
fd.sayn = sayn #sayn方法说出文本后会停顿
fd.say = fd.stdin.write #说出文本后不会停顿,加空格也不行
return fd
if __name__ == ‘__main__‘:
tts = tts_head()
tts.say(‘天气预报‘)
weather = get_weather_data()
if weather[‘status‘] != 200:
tts.say(‘天气数据获取错误‘)
for i in [‘district‘,‘dateTime‘,[‘平均温度‘,‘temp‘,‘度‘]]:#在这里定制想要的信息
if isinstance(i,list):
tts.sayn(i[0])
tts.sayn(weather[‘data‘][i[1]].encode(‘utf-8‘))
tts.say(i[2])
else:
tts.sayn(weather[‘data‘][i].encode(‘utf-8‘))
标签:
原文地址:http://www.cnblogs.com/szerr/p/4574063.html