def remove_stopwords(text,nlp,custom_stop_words=None,remove_small_tokens=True,min_len=2):
if custom_stop_words:
nlp.Defaults.stop_words |= custom_stop_words
filtered_sentence =[]
doc = nlp (text)
for token in doc:
if token.is_stop == False:
if remove_small_tokens:
if len(token.text)>min_len:
filtered_sentence.append(token.text)
else:
filtered_sentence.append(token.text)
return " ".join(filtered_sentence)
if len(filtered_sentence)>0
else None
我收到最后一个 else 的错误:
最后一部分的目标是,如果在删除停用词后,句子中仍然留有单词,则该句子应作为字符串返回,否则返回 null。我将非常感谢任何建议。
else None
^
IndentationError: expected an indented block
我猜你想使用三元运算符。
它的格式是
x if condition else y
这位于同一行,并且 if else 之后没有 :
。
所以你最后的返回语句应该是:
return " ".join(filtered_sentence) if len(filtered_sentence)>0 else None
您的整个代码没有正确缩进
def remove_stopwords(text,nlp,custom_stop_words=None,remove_small_tokens=True,min_len=2):
if custom_stop_words:
nlp.Defaults.stop_words |= custom_stop_words
filtered_sentence =[]
doc = nlp (text)
for token in doc:
if token.is_stop == False:
if remove_small_tokens:
if len(token.text)>min_len:
filtered_sentence.append(token.text)
else:
filtered_sentence.append(token.text)
if len(filtered_sentence) > 0:
return " ".join(filtered_sentence)
else:
return None