删除由正则表达式使用strip函数获得的字符串的一部分

2024-09-27 20:18:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。我有一个正则表达式,它正在查看天气的rss提要

url = 'http://rss.weatherzone.com.au/?u=12994-1285&lt=aploc&lc=9388&obs=1&fc=1&warn=1'
weather_brisbane = urlopen(url)
html_code = weather_brisbane.read()
weather_brisbane.close()

我有一个正则表达式:

weather_contents = findall('<b>(.+)</b> (.*)', html_code)
if weather_contents != []:
    print 'Contents'
    for section_heading in weather_contents:
        print section_heading 
    print

结果是:

Contents
('Temperature:', '20.1&#176;C\r')
('Feels like:', '20.1&#176;C<br />\r')
('Dew point:', '13.6&#176;C\r')
('Relative humidity:', '66%<br />\r')
('Wind:', 'E at 2 km/h, gusting to 4 km/h\r')
('Rain:', '0.0mm since 9am<br />\r')
('Pressure:', '1024.9 hPa\r')​

所以我的问题是,有没有办法得到这个结果:

Contents
Temperature: 20.1
Feels like: 20.1
Dew point: 13.6
Relative humidity: 66%
Wind: E at 2 km/h, gusting to 4 km/h
Rain: 0.0mm since 9am
Pressure: 1024.9 hPa

通过将strip()函数集成到现有代码中。你知道吗


Tags: brurlhtmlcontentscodesectionrssprint
3条回答

HTMLParser有一种替代方法:

print ' '.join([s.rstrip('\r').rsplit('<br />')[0].rsplit('&#176;C')[0] for s in section_heading])

而不是

print section_heading
weather_contents = [x.replace('&#176;C', "C") for x in weather_contents]

这将有助于改善你的天气内容

你得到的otuput似乎是html编码的。你知道吗

使用html解码器将使其:Decode HTML entities in Python string?

所以请使用以下代码:

from HTMLParser import HTMLParser
h = HTMLParser()
weather_contents = findall('<b>(.+)</b> (.*)', html_code)
if weather_contents != []:
    print 'Contents'
    for section_heading in weather_contents:
        print section_heading[0], h.unescape(section_heading[1]) 
    print

我想这会显示你想显示的内容。你知道吗

相关问题 更多 >

    热门问题