从列表中提取元素?

2024-09-27 01:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我不认为我的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('@')]

Tags: ofthe字符串inforreturntag测试用例
1条回答
网友
1楼 · 发布于 2024-09-27 01:30:09

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

它所做的是,如果在拆分的令牌中发现一个“@”字符,它将从@的下一个字母开始返回令牌。例如,如果tag='b@a123,那么它将返回tag[2:],即a123。你知道吗

相关问题 更多 >

    热门问题