python查天气预报_python查询全国天气预报

【实例简介】

【实例截图】

f5936f56c5c1e73b6e339056132db944.png

【核心代码】

from tkinter import *

import tkinter as tk

import requests

from PIL import ImageTk as itk

class MyFrame(Frame):

def __init__(self):

self.root=Tk()

self.root.title("天气查询")

self.root.geometry('1200x700 400 220')

bg = tk.Canvas(self.root, width=1200, height=600, bg='white')

#self.img = itk.PhotoImage(file="bg.gif")

#bg.place(x=100, y=40)

#bg.create_image(0, 0, anchor=NW, image=self.img)

self.city = Entry(self.root, width=16, font=("仿宋", 18, "normal"))

self.city.place(x=200, y=60)

citylabel=Label(self.root,text='查询城市',font=("仿宋", 18, "normal"))

citylabel.place(x=80,y=60)

#查询按钮

chaxun = Button(self.root, width=10, height=3, text="查询", bg='#00CCFF', bd=5, font="bold")

chaxun.bind("", self.search)

chaxun.place(x=800, y=50)

self.result=Listbox(self.root,heigh=18,width=65,font=("仿宋", 20, "normal"))#显示天气框

self.result.place(x=125,y=120)

def tianqiforecast(self,searchcity):

print('请输入所要查询天气的城市:')

city = searchcity

# city='minquan'

url = 'http://toy1.weather.com.cn/search?cityname=' city '&callback=success_jsonpCallback&_=1548048506469'

# print(url)

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',

'Cookie': '__guid=182823328.3322839646442213000.1543932524694.901; vjuids=1858d43b6.167798cbdb7.0.8c4d7463d5c5d; vjlast=1543932526.1543932526.30; userNewsPort0=1; f_city=%E5%B9%B3%E9%A1%B6%E5%B1%B1%7C101180501%7C; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1543932526,1543932551,1543932579; Wa_lvt_1=1547464114,1547464115,1547880054,1547983123; defaultCty=101181001; defaultCtyName=%u5546%u4E18; monitor_count=6; Wa_lpvt_1=1547983809'

}

response = requests.get(url, headers=headers)

html1 = response.content.decode('utf-8')

# print(html)

citys = re.findall('"ref":"(.*?)~.*?~(.*?)~.*?~(.*?)~.*?~.*?~.*?~.*?~(.*?)"', html1, re.S)

if (len(citys) == 0):

print('未查找到该城市')

exit(-5)

for i in range(0, len(citys)):

print(i 1, ':%14s%14s%14s%14s ' % (citys[i][0], citys[i][3], citys[i][2], citys[i][1]))

#choose = int(input('请选择城市编号:[1~' str(len(citys)) ']\n'))

choose=1

if (len(citys[choose - 1][0]) == 9):

if (citys[choose - 1][0][0] != '1' or citys[choose - 1][0][1] != '0' or citys[choose - 1][0][2] != '1'):

print('暂时无法查询国外天气,程序已退出')

exit(404)

else:

url2 = 'http://www.weather.com.cn/weathern/' citys[choose - 1][0] '.shtml'

responseweather = requests.get(url2, headers=headers)

html2 = responseweather.content.decode('utf-8')

weather = re.findall('

(.*?)*?"date-i.*?">(.*?)<.*?', html2, re.S)

weather.append(re.findall(

'

(.*?)

',

html2, re.S))

Hightempture = re.findall(

'

re.S)

Lowtempture = re.findall(

'var eventNight =\["(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)"\];',

html2, re.S)

# print(Hightempture,Lowtempture)

b='查询城市为:' str(citys[choose - 1][3]) ' ' str(citys[choose - 1][1])

self.result.insert(END, b)

for i in range(0, 8):

# print(weather[i])

'''print("%4s%4s%10s\t\t\t%s℃ ~ %s℃\t\t\t%s%s%-s" % (

weather[i][0], weather[i][1], weather[8][i][0], Lowtempture[0][i], Hightempture[0][i],

weather[8][i][1],

weather[8][i][3], weather[8][i][2]))'''

a = weather[i][0] ' ' weather[i][1] ' ' weather[8][i][0] ' ' Lowtempture[0][i] '℃ ~ ' \

Hightempture[0][i] '℃ ' weather[8][i][1] weather[8][i][3] weather[8][i][2]

self.result.insert(END, a)

if (len(citys[choose - 1][0]) == 12):

url2 = 'http://forecast.weather.com.cn/town/weathern/' citys[choose - 1][0] '.shtml'

responseweather = requests.get(url2, headers=headers)

html2 = responseweather.content.decode('utf-8')

weather = re.findall('

(.*?)*?"date-i.*?">(.*?)<.*?', html2, re.S)

html2 = re.sub('lt;', '<', html2)

weather.append(re.findall(

'

\\r\\n(.*?)\\r\\n',

html2, re.S))

Hightempture = re.findall(

'var eventDay = \["(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)"\];', html2, re.S)

Lowtempture = re.findall(

'var eventNight = \["(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)","(.*?)"\];',

html2, re.S)

# print(Hightempture,Lowtempture)

b='查询城市为:' str(citys[choose - 1][3]) ' ' str( citys[choose - 1][2]) ' ' str(citys[choose - 1][1])

self.result.insert(0,b)

#print(weather[8][2])

#print(weather)

for i in range(0, 8):

# print(weather[i])

'''print("%4s%4s%10s\t\t\t%s℃ ~ %s℃\t\t\t%s%s%-s" % (

weather[i][0], weather[i][1], weather[8][i][0], Lowtempture[0][i], Hightempture[0][i],

weather[8][i][1],

weather[8][i][3], weather[8][i][2]))'''

a = weather[i][0] ' ' weather[i][1] ' ' weather[8][i][0] ' ' Lowtempture[0][i] '℃ ~ ' \

Hightempture[0][i] '℃ ' weather[8][i][1] weather[8][i][3] weather[8][i][2]

self.result.insert(END, a)

def search(self,event):

mycity=self.city.get()

if(mycity!=''):

self.result.delete(0,END)

self.city.delete(0,END)

self.tianqiforecast(mycity)

if __name__=='__main__':

myframe=MyFrame()

myframe.root.mainloop()

好的,我可以为您提供一些参考代码和思路。 首先,您可以使用Python中的requests库获取天气预报的数据。根据您所在的地理位置和天气数据源,您可能需要使用不同的API接口,例如OpenWeatherMap、中国天气网等。在获取到天气数据之后,您可以使用Python中的json库或xml库来解析数据。 接着,您可以使用Python中的pygame库来播放语音。将天气预报转换为语音文件的方法有很多种,例如使用百度AI开放平台的语音合成API、使用Google Text-to-Speech API等。其中,百度AI开放平台的语音合成API使用起来比较方便,具体使用方法可以参考官方文档。 最后,您可以将获取到的天气数据和语音播放代码结合起来,实现天气预报语音播报的功能。 下面是一个简单的示例代码,供您参考: ```python import requests import json import pygame from aip import AipSpeech # 获取天气预报数据 weather_api_url = 'http://api.openweathermap.org/data/2.5/weather?q=city_name&appid=api_key' city_name = 'Shanghai' # 城市名称 api_key = 'your_api_key' # API密钥 url = weather_api_url.replace('city_name', city_name).replace('api_key', api_key) response = requests.get(url) weather_data = json.loads(response.text) # 解析天气预报数据 temperature = weather_data['main']['temp'] - 273.15 # 温度(单位:摄氏度) description = weather_data['weather'][0]['description'] # 天气描述 # 将天气预报转换为语音 APP_ID = 'your_app_id' # APP ID API_KEY = 'your_api_key' # API密钥 SECRET_KEY = 'your_secret_key' # 密钥 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) result = client.synthesis('今天的天气是' + description + ',温度是' + str(round(temperature, 1)) + '摄氏度。', 'zh', 1, {'vol': 5}) if not isinstance(result, dict): with open('weather.mp3', 'wb') as f: f.write(result) # 播放语音 pygame.mixer.init() pygame.mixer.music.load('weather.mp3') pygame.mixer.music.play() while pygame.mixer.music.get_busy() == True: continue ``` 需要注意的是,该示例代码使用了百度AI开放平台的语音合成API,您需要在使用之前去官网注册账号并申请API密钥。另外,该示例代码使用了pygame库来播放语音,如果您使用的是其他的播放音频的库,则可能需要进行相应的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值