PythonTip >> 博文 >> python

Python获取Yahoo天气

zihua 2014-01-20 23:01:56 点击: 1014 | 收藏


前几天看到荒野无灯同学写了Java利用yahoo weather api获取天气预报。方法是通过 GeoPlanet api 来查询相应地点的WOEID了,然后利用yahoo weather api:http://weather.yahooapis.com/forecastrss?w=woeid&u=c获取天气信息,其中w的值为你呀查询地点的woeid。各地的woeid我是让荒野无灯同学把中国区的部分传给我。你也可以自己去下载。里面的字段如下:

WOE_ID ISO Name Language PlaceType Parent_ID

为了便于查询,我将这些数据保存到Sqlite数据库中。数据库表格数据项:

CREATE TABLE "yahoo" (
     "woeid" VARCHAR PRIMARY KEY  NOT NULL ,
     "iso" VARCHAR,
     "name" VARCHAR,
     "language" VARCHAR,
     "placetype" VARCHAR,
     "paraentid" VARCHAR
)

导入方法可以参考Sqlite导入cvs文件,或者自己写一段代码:

from sqlite3 import *
conn = connect('test.db')
conn.text_factory = str
curs = conn.cursor()
file = open('test.txt')
for line in file.readlines():
    data = line.split("\t")
    sql = "insert into yahoo(woeid,iso,name,language,placetype,paraentid) values ('%s','%s','%s','%s','%s','%s')"%(str(data[0]),str(data[1][1:-1]),str(data[2][1:-1]),str(data[3]),str(data[4]),str(data[5]))
    curs.execute(sql)
conn.commit()
file.close()
conn.close()

导入之后便可用于查询,根据用户输入返回该城市或者地区的woeid:

def findWoeidFromDB(city):
    database = "test.db"
    if not os.path.isfile(database):
        print "database already exists"
    conn = sqlite3.connect(database)
    conn.text_factory = str
    curs = conn.cursor()
    code = ''
    try:
        if city != '':
            curs.execute("select * from yahoo where name like'%%%s%%'"%(city))
    except sqlite3.OperationalError, msg:
        print msg
    for row in curs:#need to be improved
        code = row[0]
    conn.close()
    return code

接着利用返回的woeid,利用yahoo weather api查询天气信息:

def readDataFromRSS(code):
    url = "http://weather.yahooapis.com/forecastrss?w=%s&u=c" % code
    try:
        sock =  urllib2.urlopen(url)
    except urllib2.URLError,msg:
        print msg
    data = sock.read()
    #print data
    dom = parseString(data)
    for i in range(2):#today and tomorrow
        xmlTag  = dom.getElementsByTagName('yweather:forecast')[i]
        codeIndex = xmlTag.getAttribute('code')
        text.insert(END,"%s: %s 最低温度:%s 最高温度:%s\n" % (dictionaryDay[i],dictionaryStrings[int(codeIndex)],xmlTag.getAttribute('low'),xmlTag.getAttribute('high')))

最后再写一个简单的界面:

root = Tk()
upFrame = Frame(root)
upFrame.pack()
downFrame = Frame(root)
downFrame.pack(side =BOTTOM)
l1 = Label(upFrame, text = "City Name")
l1.pack(side = LEFT)
e1 = Entry(upFrame)
e1.pack(side=LEFT)
b1 = Button(upFrame,text="Search", command =doSearch )
b1.pack(side = LEFT)
text = Text(downFrame)
text.pack(side = BOTTOM)
root.mainloop()

效果展示:

雅虎天气

源码和中国区woeid资料下载:金山快盘

原文链接:http://www.wumii.com/item/4roCqcNf

作者:zihua | 分类: python | 标签: python | 阅读: 1014 | 发布于: 2014-01-20 23时 |