从特定字符开始删除令牌

时间:2017-01-29 05:10:18

标签: python string tokenize

您好我正在尝试删除我预定义列表(前缀)中包含的所有令牌。下面是我的代码,并没有删除令牌。

prefixes = ('#', '@')
tokens = [u'order', u'online', u'today', u'ebay', u'store', u'#hamandcheesecroissant', u'#whoopwhoop', u'\u2026']

for token in tokens:
    if token.startswith(prefixes):
       tokens.remove(token)

1 个答案:

答案 0 :(得分:3)

在迭代它时,从列表中删除项目并不真正有用。

您可以使用列表理解

tokens = [token for token in tokens if not token.startswith(prefixes)]

或者创建另一个列表,然后将要保留的项目添加到该列表中:

new_tokens = []

for token in tokens:
    if not token.startswith(prefixes):
       new_tokens.append(token)