用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


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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值