python实现输入城市查询天气
最近在學(xué)習(xí)用python調(diào)用webservice接口后,經(jīng)過測試和舉例,做簡單的數(shù)據(jù)解析,得到輸入城市查詢天氣的代碼。
可以查看如何用python調(diào)用webservice接口文章,以及通過城市查詢天氣報type not found錯誤。
輸入城市名稱獲取天氣
from suds.client import Client from suds.xsd.doctor import ImportDoctor,Import url = 'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl' imp = Import('http://www.w3.org/2001/XMLSchema',location='http://www.w3.org/2001/XMLSchema.xsd') imp.filter.add('http://WebXml.com.cn/') c = Client(url,doctor = ImportDoctor(imp)) print(c.service.getWeatherbyCityName(u"成都")運行上述代碼,我們發(fā)現(xiàn)得到很多數(shù)據(jù),有些數(shù)據(jù)用不著,比如圖片,風(fēng)向,結(jié)果如下
解析數(shù)據(jù)
①為了友好體驗,將城市名弄成可輸入類型
city_name = input("請輸入城市名(按Enter結(jié)束):")②將通過接口返回的數(shù)據(jù)類型轉(zhuǎn)換成字符類型,然后再截取我們想要的數(shù)據(jù)。因為我們需要的數(shù)據(jù)是從string[]=開始,因此我們截取之后的數(shù)據(jù),因此就有了以下代碼
from suds.client import Client from suds.xsd.doctor import ImportDoctor,Import url = 'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl' imp = Import('http://www.w3.org/2001/XMLSchema',location='http://www.w3.org/2001/XMLSchema.xsd') imp.filter.add('http://WebXml.com.cn/') c = Client(url,doctor = ImportDoctor(imp)) city_name = input("請輸入城市名(按Enter結(jié)束):") message = str(c.service.getWeatherbyCityName(city_name)) message = message.split("string[] =")[-1] print(message)得到結(jié)果如下字符串,發(fā)現(xiàn)存在換行符和多與的符號
③ 替換多余的換行符合、空格、引號
替換后的數(shù)據(jù)看起來雖然不太好看,至少更明確了,name就來得到自己想要的數(shù)據(jù)吧
④根據(jù)逗號分離,得到自己想要獲取的數(shù)據(jù),我是自己組成字典看起來明確一點,最終如下
鐺鐺,以下就是我想要的最終結(jié)果
將py文件打包成exe來執(zhí)行
注意,打包是需要安裝pyinstaller來執(zhí)行打包,為了使提示更加持久,用tkinter給了Windows彈框,注意python2是TKinter。至于安裝pyinstaller出錯了的話,可以查看安裝pyinstaller,完整代碼如下
from suds.client import Client from suds.xsd.doctor import ImportDoctor,Import import tkinter.messagebox url = 'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl' imp = Import('http://www.w3.org/2001/XMLSchema',location='http://www.w3.org/2001/XMLSchema.xsd') imp.filter.add('http://WebXml.com.cn/') c = Client(url,doctor = ImportDoctor(imp)) city_name = input("請輸入城市名(按Enter結(jié)束):") message = str(c.service.getWeatherbyCityName(city_name)) message = message.split("string[] =")[-1] message = message.replace("\n", "").replace(" ", "").replace('"', "") message_list = [] message_list += message.split(",") message_dict = {"城市": a[1], "查詢時間": a[4], "天氣": a[6], "溫度": a[5]} tkinter.messagebox.showinfo(message=message_dict)如上代碼,最終執(zhí)行時exe文件時,在Windows彈框內(nèi)容如下。等熟悉tkinter后再來優(yōu)化最后一步,先這樣吧
總結(jié)
以上是生活随笔為你收集整理的python实现输入城市查询天气的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux桌面环境组件下载,万能桌面小组
- 下一篇: 跳一跳python源码下载_微信跳一跳辅