用python写一段查天气的代码

微博号:暖风_lin
本人小菜,有问题可以微博私信互相讨论一下,谢谢;

代码为python2.7 运行环境在python自带的IDLE里头,代码如下:

# -*- coding: utf-8 -*-
import urllib2
import json
from city import city                    //引入各模块;
bingo = True                             //设置标记;
while bingo == True:
    cityname = raw_input('which city do you want to know,you can use chinese\n')
    citycode = city.get(cityname)        //以下为查询代码:
    if citycode:
        try:                             //try语句避免查询不到的情况
            url = ('http://www.weather.com.cn/data/cityinfo/%s.html'
               %citycode)
            content = urllib2.urlopen(url).read()
            data = json.loads(content)
            result = data['weatherinfo']
            str_temp = ('%s\n%s~%s')%(
                result['weather'],
                result['temp1'],
                result['temp2']
                )
            print str_temp
        except:
            print 'sorry,fail to found~'
    else:
        print'do not found the city!'
    print'continue to search?Y/N'
    go = raw_input()
    if go == 'N':
        bingo = False


运行结果:用python写一段查天气的代码_第1张图片
数据来源于中国天气网;
运行需要各个地方的编码数据:
有抓完的包,在网盘里:
http://pan.baidu.com/share/link?shareid=1471212773&uk=204484850
运行程序的时候注意要把city.py和这个文件放在一个文件目录里面哈。

你可能感兴趣的:(python,代码,天气查询,生活)