Skip to main content
 首页 » 编程设计

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

2024年11月01日28kevingrace

我有一个问题。我有一个正则表达式,它通过 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() 函数集成到现有代码中。

请您参考如下方法:

HTMLParser 有一个替代方案:

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

代替

print section_heading