如何对两个或更多while循环使用'remove()'方法而不使用ValueError?

2024-04-25 12:44:58 发布

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


Tags: python
2条回答

因为您似乎想从给定的一组令牌中排除所有令牌,所以在创建toks列表时忽略它们更容易:

from spacy.en import English

unwanted_tokens = {'?', ',', 'you'}

text = u"Hey, there, hope you are doing good??????  or maybe not?"
nlp = English()
tokens = nlp(text)
toks = []
for t in tokens:
    if t.lower_ not in unwanted_tokens:
        toks.append(t.lower_)

>>> toks
[u'hey', u'there', u'hope', u'are', u'doing', u'good', u' ', u'or', u'maybe', u'not']

for循环可以替换为列表:

toks = [t.lower_ for t in tokens if t.lower_ not in unwanted_tokens]

如果由于问题中没有显示的原因,必须在创建toks之后删除标记,则可以使用列表理解:

toks = [t for t in toks if t not in unwanted_tokens]

使用^{}方法,将空字符串作为新字符串。你知道吗

for target in ['?', ',', 'you']:
    text = text.replace(target, '')

它所做的是遍历需要替换的项,并在每次看到该字符串时插入空字符串

相关问题 更多 >