好吧,这里是 – 针对您的特定情况的非完整解析器解决方案:

import urllib

def getWeather(city):

''' given city name or postal code,

return dictionary with current weather conditions

'''

url = 'http://www.google.com/ig/api?weather='

try:

f = urllib.urlopen(url + urllib.quote(city))

except:

return "Error opening url"

s = f.read().replace('\r','').replace('\n','')

if '

return "Problem retreaving weather (invalid city?)"

weather = s.split('')[0] \

.split('')[-1] \

.strip('>')

wdict = dict(i.split(' data="') for i in weather.split('"/>

return wdict

和使用的例子:

>>> weather = getWeather('94043')

>>> weather

{'temp_f': '67', 'temp_c': '19', 'humidity': 'Humidity: 61%', 'wind_condition': 'Wind: N at 21 mph', 'condition': 'Sunny', 'icon': '/ig/images/weather/sunny.gif'}

>>> weather['humidity']

'Humidity: 61%'

>>> print '%(condition)s\nTemperature %(temp_c)s C (%(temp_f)s F)\n%(humidity)s\n%(wind_condition)s' % weather

Sunny

Temperature 19 C (67 F)

Humidity: 61%

Wind: N at 21 mph

PS.请注意,谷歌输出格式的一个相当微不足道的变化将打破这一点 – 比如他们是在标签或属性之间添加额外的空格或标签.他们避免减少http响应的大小.但如果他们这样做了,我们必须熟悉正则表达式和re.split()

PPS. str.split(sep)的工作方式在文档中有解释,这里有一段摘录:使用sep作为分隔符字符串,返回字符串中单词的列表. … sep参数可以包含多个字符(例如,’1<><>>>’>’<>‘)返回[‘1′,’2′,’3’] ).所以’text1< tag> text2< / tag> text3′.split(‘< / tag>‘)给我们[‘text1< tag> text2′,’text3′],然后[0]选择第一个元素’ text1< tag> text2′,然后我们拆分并选取’text2′,其中包含我们感兴趣的数据.真的非常陈词滥调.

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐