栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何实现python在xml标签之间查找值?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何实现python在xml标签之间查找值?

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

import urllibdef getWeather(city):    ''' given city name or postal pre,        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 '<problem' in s:        return "Problem retreaving weather (invalid city?)"    weather = s.split('</current_conditions>')[0]      .split('<current_conditions>')[-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)snTemperature %(temp_c)s C (%(temp_f)s F)n%(humidity)sn%(wind_condition)s' % weatherSunnyTemperature 19 C (67 F)Humidity: 61%Wind: N at 21 mph

PS。请注意,对Google输出格式进行相当琐碎的更改将打破这种情况-
例如,如果他们要在标签或属性之间添加额外的空格或制表符。他们避免减小HTTP响应的大小。但是,如果这样做,我们必须熟悉正则表达式和re.split()

PPS。

str.split(sep)
文档中解释了工作原理,以下是摘录: 使用sep作为分隔符字符串,返回字符串中单词的列表。…
sep参数可能包含多个字符(例如‘1 <> 2 <>
3’.split(’<>’)返回[‘1’,‘2’,‘3’])

。因此
'text1<tag>text2</tag>text3'.split('</tag>')
给我们
['text1<tag>text2','text3']
,然后
[0]
选取第一个元素
'text1<tag>text2'
,然后在处拆分并选取“
text2”,其中包含我们感兴趣的数据。确实很陈旧。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号