Python 从列表中提取元素?

Python 从列表中提取元素?,python,string,list,twitter,element,Python,String,List,Twitter,Element,我不认为我的return语句通过了所有测试用例(带有空字符串的测试用例)。@FLOTUS不是一个提及,因为提及应该是一个空格,或者更确切地说是一条tweet的开始。因此,它应该作为空字符串传递。任何关于如何修复此问题的帮助都将不胜感激 def extract_mentions(tweet): ''' (str) -> list of str Return a list containing all of the mentions in the tweet, in the orde

我不认为我的return语句通过了所有测试用例(带有空字符串的测试用例)。@FLOTUS不是一个提及,因为提及应该是一个空格,或者更确切地说是一条tweet的开始。因此,它应该作为空字符串传递。任何关于如何修复此问题的帮助都将不胜感激

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('@')]

就我个人而言,我倾向于使用Wiktor在评论中提出的一个很好的正则表达式,但如果您想避免使用它,请尝试使用
[tag[tag.index('@')+1:]作为tweet.split()中的标记(如果标记中有'@'))


这样做的目的是,如果它在拆分的令牌中找到一个“@”字符,它将从@的下一个字母开始返回该令牌。例如,如果
tag=b@a123
然后它将返回
标记[2:][/code>,它是a123。

你不能只使用
re.findall(r'\B@\w+',tweet)
?为什么最后一个示例返回一个包含空字符串的列表?它不应该返回一个空列表——一个包含所有(零)提及的列表吗?但我还想删除标点符号,例如@ohio!我怎样才能在函数调用中实现它呢?我个人会在新的标记列表中分离我的关注点并过滤标点符号,而不是在开始时,因为你只需要清理几个提到的标记。