【发布时间】:2014-06-24 18:28:02
【问题描述】:
我正在清理 Twitter 流中的一系列来源。 以下是数据示例:
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 感谢您的评论。
[^>]*的解释是什么? -
查看我的答案,它匹配任何不是
>的字符,这意味着您上下文中标签内的所有内容。
标签: python html regex html-parsing