Python 查询各地天气情况
Python的学习在不断进行中,对于零基础自学者而言,我还是从一些有意思的小程序着手学习它,今天修改了一个天气查询的小程序,主要涉及urllib、file等的修改,因为我用的是python3!作为初学者想更好的了解Python的使用,多研究小程序很有帮助。下面是Python天气查询小程序的代码:
#!/usr/bin/env python #coding=utf-8 import urllib.request ,sys import re provice=input('输入省名(请使用拼音):'); major=input("输入市名(请使用拼音):") url="http://qq.ip138.com/weather/"+provice+'/'+major+'.htm' print(url) #url="http://www.baidu.com" #www.basemu.com wetherhtml=urllib.request.urlopen(url) result=wetherhtml.read().decode('GB2312')#.encode('utf-8') #result=result.replace("gb2312","utf-8") f=open('weather.txt','wb') f.write(result.encode('GB2312')) f.close() pattern='Title.+(.+)' Title=re.search(pattern,result).group(1) pattern='>(\d*-\d*-\d*.+?)<' date=re.findall(pattern,result) pattern='alt="(.+?)"' weather=re.findall(pattern,result) pattern='([-]?\d{1,2}.+) temperature=re.findall(pattern,result) print("%35.30s"%Title,"") length=len(date) for i in range(length): print('%30.20s'%date[i],'\t%s'%weather[i],'\t%s'%temperature[i])
小程序的使用
我们可以将上面的代码复制后,存为一个你喜欢的名字,例如study python.py或者weather.py,涉及的修改是python3中urllib需要修改为urllib.request,“import urllib.request”;f=open(‘weather.txt’,’w’)修改为f=open(‘weather.txt’,’wb’)。然后我们通过python的IDLE打开它,运行”Run Module”或者直接F5即可。