zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    树形地铁系统[树的最小表示]
    156. 矩阵[二维的hash]
    兔子与兔子
    滑动窗口【单调队列入门题】
    【YBTOJ】生日相同
    【YBTOJ】移位包含
    【YBTOJ】【HDUOJ 3085】逃离噩梦
    【YBTOJ】立体推箱子
    【CodeForces 1408F】Two Different
    【Luogu P3338】[ZJOI2014]力
  • 原文地址:https://www.cnblogs.com/jackyshan/p/3545459.html
Copyright © 2011-2022 走看看