我正在清理twitter流中的一系列來源。 下面是數據的一個例子:更好的使用方法re.sub
source = ['<a href="https://twitter.com/download/android" rel="nofollow">Twitter for Android Tablets</a>',
'<a href="https://twitter.com/download/android" rel="nofollow">Twitter for Android</a>',
'<a href="http://foursquare.com" rel="nofollow">foursquare</a>', 'web',
'<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
'<a href="http://blackberry.com/twitter" rel="nofollow">Twitter for BlackBerry</a>']
import re
for i in source:
re.sub('<.*?>', '', re.sub(r'(<.*?>)(Twitter for)(\s+)', r'', i))
### This would be the expected output ###
'Android Tablets'
'Android'
'foursquare'
'web'
'iPhone'
'BlackBerry'
後者是代碼我有沒有工作,但看起來可怕。我希望有一個更好的方法來做到這一點,包括re.sub()
或其他更適合的功能。
'S [s.index( '>')+ 1:s.rindex( '<')]'。順便說一下:而不是'。*?'我會使用'[^>] *'。 – Bakuriu
不錯的codegolf! :) – TML
@Bakuriu thx的評論。 '[^>] *'的解釋是什麼? – marbel