• 使用python查询天气


    python主代码

    weather.py 


    import urllib2
    import json
    from city import city

    cityname = raw_input('你想查哪个城市的天气? ')
    citycode = city.get(cityname)
    if citycode:
       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 %s ~ %s') % (
           result['weather'],
           result['temp2'],
           result['temp1']
           )
       print str_temp

     抓取city.py的数据代码 

    import urllib2

    url1 = 'http://m.weather.com.cn/data5/city.xml'
    content1 = urllib2.urlopen(url1).read()
    provinces = content1.split(',')
    result = 'city = { '
    url = 'http://m.weather.com.cn/data3/city%s.xml'
    for p in provinces:
        p_code = p.split('|')[0]
        url2 = url % p_code
        content2 = urllib2.urlopen(url2).read()
        cities = content2.split(',')
        for c in cities:
            c_code = c.split('|')[0]
            url3 = url % c_code
            content3 = urllib2.urlopen(url3).read()
            districts = content3.split(',')
            for d in districts:
                d_pair = d.split('|')
                d_code = d_pair[0]
                name = d_pair[1]
                url4 = url % d_code
                content4 = urllib2.urlopen(url4).read()
                code = content4.split('|')[1]
                line = "    '%s': '%s', " % (name, code)
                result += line
                print  name + ':' + code
    result += '}'
    f = file('/home/crossin/Desktop/city.py''w')
    f.write(result)
    f.close()

    city.py

    http://pan.baidu.com/share/link?shareid=1471212773&uk=204484850

  • 相关阅读:
    php javascript
    在线支付接口之PHP支付宝接口开发
    作业9 最长公共子序列
    第十二章 税制的设计
    第十一章 公共物品和公共资源
    第十章 外部性
    第九章 应用:国际贸易
    作业8 矩阵乘法链
    第八章 应用:赋税的代价
    第七章 消费者、生产者与市场效率
  • 原文地址:https://www.cnblogs.com/jackyshan/p/3545459.html
Copyright © 2020-2023  润新知