python实现智能语音天气预报


Posted in Python onDecember 02, 2019

python编写的语音天气预报

本系统主要包括四个函数:

1、获取天气数据

1、输入要查询天气的城市

2、利用urllib模块向中华万年历天气api接口请求天气数据

3、利用gzip解压获取到的数据,并编码utf-8

4、利用json转化成python识别的数据,返回为天气预报数据复杂形式的字典(字典中的字典)

2、输出当天天气数据

1、格式化输出当天天气,包括:天气状况,此时温度,最高温度、最低温度,风级,风向等。

3,语音播报当天天气

1、创建要输出的语音文本(weather_forecast_txt)

2、利用百度的语音合成模块AipSpeech,合成语音文件

3,利用playsound模块播放语音

4、未来几天温度变化趋势

1、创建未来几天高低温数据的字典

2,利用matplotlib模块,图形化温度变化趋势

5、代码

#导入必要模块
import urllib.parse
import urllib.request
import gzip
import json
import playsound
from aip import AipSpeech
import matplotlib.pyplot as plt
import re
#设置参数,图片显示中文字符,否则乱码
plt.rcParams['font.sans-serif']=['SimHei']
#定义获取天气数据函数
def Get_weather_data():
  print('------天气查询------')
  city_name = input('请输入要查询的城市名称:')
  url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name)
  weather_data = urllib.request.urlopen(url).read()
  # 读取网页数据
  weather_data = gzip.decompress(weather_data).decode('utf-8')
  # #解压网页数据
  weather_dict = json.loads(weather_data)
  return weather_dict
#定义当天天气输出格式
def Show_weather(weather_data):
  weather_dict = weather_data
  if weather_dict.get('desc') == 'invilad-citykey':
    print('你输入的城市有误或未收录天气,请重新输入...')
  elif weather_dict.get('desc') == 'OK':
    forecast = weather_dict.get('data').get('forecast')
    print('日期:', forecast[0].get('date'))
    print('城市:', weather_dict.get('data').get('city'))
    print('天气:', forecast[0].get('type'))
    print('温度:', weather_dict.get('data').get('wendu') + '℃ ')
    print('高温:', forecast[0].get('high'))
    print('低温:', forecast[0].get('low'))
    print('风级:', forecast[0].get('fengli').split('<')[2].split(']')[0])
    print('风向:', forecast[0].get('fengxiang'))
    weather_forecast_txt = '您好,您所在的城市%s,' \
                '天气%s,' \
                '当前温度%s,' \
                '今天最高温度%s,' \
                '最低温度%s,' \
                '风级%s,' \
                '温馨提示:%s' % \
                (
                  weather_dict.get('data').get('city'),
                  forecast[0].get('type'),
                  weather_dict.get('data').get('wendu'),
                  forecast[0].get('high'),
                  forecast[0].get('low'),
                  forecast[0].get('fengli').split('<')[2].split(']')[0],
                  weather_dict.get('data').get('ganmao')
                )
    return weather_forecast_txt,forecast
#定义语音播报今天天气状况
def Voice_broadcast(weather_forcast_txt):
  weather_forecast_txt = weather_forcast_txt
  APP_ID = 你的百度语音APP_ID
  API_KEY = 你的百度语音API_KEY
  SECRET_KEY = 你的百度语音SECRET_KEY
  client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
  print('语音提醒:', weather_forecast_txt)
  #百度语音合成
  result = client.synthesis(weather_forecast_txt, 'zh', 1, {'vol': 5})
  if not isinstance(result, dict):
    with open('sound2.mp3', 'wb') as f:
      f.write(result)
      f.close()
  #playsound模块播放语音
  playsound.playsound(r'C:\Users\ban\Desktop\bsy\sound2.mp3')
#未来四天天气变化图
def Future_weather_states(forecast):
  future_forecast = forecast
  dict={}
  #获取未来四天天气状况
  for i in range(5):
    data = []
    date=future_forecast[i]['date']
    date = int(re.findall('\d+',date)[0])
    data.append(int(re.findall('\d+',future_forecast[i]['high'])[0]))
    data.append(int(re.findall('\d+', future_forecast[i]['low'])[0]))
    data.append(future_forecast[i]['type'])
    dict[date] = data
  data_list = sorted(dict.items())
  date=[]
  high_temperature = []
  low_temperature = []
  for each in data_list:
    date.append(each[0])
    high_temperature.append(each[1][0])
    low_temperature.append(each[1][1])
  fig = plt.plot(date,high_temperature,'r',date,low_temperature,'b')
  plt.xlabel('日期')
  plt.ylabel('℃')
  plt.legend(['高温','低温'])
  plt.xticks(date)
  plt.title('最近几天温度变化趋势')
  plt.show()
#主函数
if __name__=='__main__':
  weather_data = Get_weather_data()
  weather_forecast_txt, forecast = Show_weather(weather_data)
  Future_weather_states(forecast)
  Voice_broadcast(weather_forecast_txt)

6、最终效果

python实现智能语音天气预报

以上这篇python实现智能语音天气预报就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python获取SQLite查询结果表列名的方法
Jun 21 Python
轻松实现TensorFlow微信跳一跳的AI
Jan 05 Python
利用python将json数据转换为csv格式的方法
Mar 22 Python
python之文件读取一行一行的方法
Jul 12 Python
Python+Pandas 获取数据库并加入DataFrame的实例
Jul 25 Python
在numpy矩阵中令小于0的元素改为0的实例
Jan 26 Python
用python给自己做一款小说阅读器过程详解
Jul 11 Python
python傅里叶变换FFT绘制频谱图
Jul 19 Python
python类的实例化问题解决
Aug 31 Python
windows支持哪个版本的python
Jul 03 Python
通过代码实例解析Pytest运行流程
Aug 20 Python
Python用Jira库来操作Jira
Dec 28 Python
Python:二维列表下标互换方式(矩阵转置)
Dec 02 #Python
python 实现二维列表转置
Dec 02 #Python
python列表推导式入门学习解析
Dec 02 #Python
Python 矩阵转置的几种方法小结
Dec 02 #Python
numpy.transpose()实现数组的转置例子
Dec 02 #Python
Python中低维数组填充高维数组的实现
Dec 02 #Python
python函数声明和调用定义及原理详解
Dec 02 #Python
You might like
PHP 编程请选择正确的文本编辑软件
2006/12/21 PHP
解决dede生成静态页和动态页转换的一些问题,及火车采集入库生成动态的办法
2007/03/29 PHP
php 短链接算法收集与分析
2011/12/30 PHP
Opcache导致php-fpm崩溃nginx返回502
2015/03/02 PHP
PHP基于cookie与session统计网站访问量并输出显示的方法
2016/01/15 PHP
PHP实现限制IP访问的方法
2017/04/20 PHP
动态改变textbox的宽高的js
2006/10/26 Javascript
通过event对象的fromElement属性解决热区设置主实体的一个bug
2008/12/22 Javascript
使用jQuery validate 验证注册表单实例演示
2013/03/25 Javascript
怎么判断js脚本加载完成
2014/02/28 Javascript
浅谈JavaScript的Polymer框架中的事件绑定
2015/07/29 Javascript
JavaScript Math.round() 方法
2015/12/18 Javascript
Angularjs手动解析表达式($parse)
2016/10/12 Javascript
JS实战篇之收缩菜单表单布局
2016/12/10 Javascript
BootStrap Table后台分页时前台删除最后一页所有数据refresh刷新后无数据问题
2016/12/28 Javascript
jquery 键盘事件的使用方法详解
2017/09/13 jQuery
微信小程序和H5页面间相互跳转代码实例
2019/09/19 Javascript
微信小程序自定义头部导航栏(组件化)
2019/11/15 Javascript
原生js实现ajax请求和JSONP跨域请求操作示例
2020/03/14 Javascript
[41:52]2018DOTA2亚洲邀请赛3月29日小组赛B组Effect VS Secret
2018/03/30 DOTA
python原始套接字编程示例分享
2014/02/21 Python
简单介绍Ruby中的CGI编程
2015/04/10 Python
批量获取及验证HTTP代理的Python脚本
2017/04/23 Python
详解Python进程间通信之命名管道
2017/08/28 Python
python执行精确的小数计算方法
2019/01/21 Python
如何用C代码给Python写扩展库(Cython)
2019/05/17 Python
python双端队列原理、实现与使用方法分析
2019/11/27 Python
详解python破解zip文件密码的方法
2020/01/13 Python
HTML+CSS+JavaScript实现图片3D展览的示例代码
2020/10/12 HTML / CSS
htmlentities() 和 htmlspecialchars()有什么区别
2015/07/01 面试题
销售员自我评价怎么写
2013/09/19 职场文书
实习生自我评价
2014/01/18 职场文书
简历自我评价模版
2014/01/31 职场文书
学校法制宣传月活动总结
2014/07/03 职场文书
Python如何把不同类型数据的json序列化
2021/04/30 Python
Django+Celery实现定时任务的示例
2021/06/23 Python