从列表中提取元素?

时间:2016-11-29 21:40:55

标签: python string list twitter element

我不认为我的return语句会传递所有测试用例(带有空字符串的测试用例)。 @FLOTUS没有提及,因为提及应该以空格进行,或者更确切地说是推文的开头。所以它应该作为一个空字符串传递。任何帮助将不胜感激如何解决这个问题!

def extract_mentions(tweet):
    ''' (str) -> list of str

Return a list containing all of the mentions in the tweet, in the order, they appear in the tweet.
Note: This definition of a mention doesn't allow for mentions embedded in other symbols.

Note: This definition of a mention doesn't allow for mentions embedded in other symbols.

>>> extract_mentions('@AndreaTantaros - You are a true journalistic professional. I so agree with what you say. Keep up the great work! #MakeAmericaGreatAgain')
['AndreaTantaros']
>>> extract_mentions('I'm joining @PhillyD tonight at 7:30 pm PDT / 10:30 pm EDT to provide commentary on tonight's #debate. Watch it here.')
['PhillyD']
>>> extract_mentions('Join me live in @Springfield, @ohio!')
['Springfield, ohio']
>>> extract_mentions('They endured beatings and jail time. They sacrificed their lives for this right@FLOTUS')
[''] '''

return [tag.strip('@') for tag in tweet.split() if tag.startswith('@')]

1 个答案:

答案 0 :(得分:0)

就个人而言,我会按照Wiktor评论中提出的一个很好的正则表达方式,但如果你想避免它,请尝试[tag[tag.index('@')+1:] for tag in tweet.split() if '@' in tag]

这样做,如果它在分割的标记中找到一个'@'字符,它将从@及其后的下一个字母返回该标记。例如,如果tag='b@a123,它将返回tag[2:],即a123。