python实现输入城市查询天气
生活随笔
收集整理的這篇文章主要介紹了
python实现输入城市查询天气
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近在學習用python調用webservice接口后,經過測試和舉例,做簡單的數據解析,得到輸入城市查詢天氣的代碼。
可以查看如何用python調用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"成都")運行上述代碼,我們發現得到很多數據,有些數據用不著,比如圖片,風向,結果如下
解析數據
①為了友好體驗,將城市名弄成可輸入類型
city_name = input("請輸入城市名(按Enter結束):")②將通過接口返回的數據類型轉換成字符類型,然后再截取我們想要的數據。因為我們需要的數據是從string[]=開始,因此我們截取之后的數據,因此就有了以下代碼
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結束):") message = str(c.service.getWeatherbyCityName(city_name)) message = message.split("string[] =")[-1] print(message)得到結果如下字符串,發現存在換行符和多與的符號
③ 替換多余的換行符合、空格、引號
替換后的數據看起來雖然不太好看,至少更明確了,name就來得到自己想要的數據吧
④根據逗號分離,得到自己想要獲取的數據,我是自己組成字典看起來明確一點,最終如下
鐺鐺,以下就是我想要的最終結果
將py文件打包成exe來執行
注意,打包是需要安裝pyinstaller來執行打包,為了使提示更加持久,用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結束):") 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)如上代碼,最終執行時exe文件時,在Windows彈框內容如下。等熟悉tkinter后再來優化最后一步,先這樣吧
總結
以上是生活随笔為你收集整理的python实现输入城市查询天气的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux桌面环境组件下载,万能桌面小组
- 下一篇: 跳一跳python源码下载_微信跳一跳辅