首页 > 解决方案 > 删除 Python 列表中的前导/尾随停用词

问题描述

while我有一个小问题,需要使用以下解决方案使用循环删除前导和尾随停用词:

from nltk.corpus import stopwords

cached_stop_words = stopwords.words("english")

text = "a the sky is the blue the a a"
tokens = text.split(" ")

start_idx, end_idx = 0, len(tokens) - 1
while start_idx < len(tokens) and tokens[start_idx] in cached_stop_words:
    start_idx += 1
while end_idx >= 0 and tokens[end_idx] in cached_stop_words:
    end_idx -= 1

new_tokens = tokens[start_idx: end_idx + 1] if start_idx < end_idx + 1 else []
print(new_tokens)

此代码的输出是一个标记列表,['sky', 'is', 'the', 'blue']因为前导和尾随停用词已被删除。请注意,令牌the不会被删除,因为它位于非停用词skyblue. 该代码有效,但效率不高。我们可以使用正则表达式或任何优化的方法来解决这个问题吗?

标签: pythonliststop-words

解决方案


推荐阅读