python - 删除 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
不会被删除,因为它位于非停用词sky
和blue
. 该代码有效,但效率不高。我们可以使用正则表达式或任何优化的方法来解决这个问题吗?
解决方案
推荐阅读
- opentok - 使用 tokbox api 流式传输 pdf 或图像
- c++ - 对有关“按引用调用函数”的声明感到困惑。
- applescript - 链接到转义键的对话框“取消”按钮
- mysql - 存储具有可变数量字段的电子邮件列表
- case-sensitive - 如何使 spaCy 不区分大小写
- json - 有没有办法如何使用带有 sqlite 后端的 flask_sqlalchemy 保存 json
- html - 每次我想向我的网站添加文章时,是否需要修改我的 HTML 文档?
- windows - 从批处理变量的文件名中提取一个部分
- unity3d - 如何让玩家能够在 Unity 中围绕立方体旋转相机?
- java - Java Web Start - 线程“AWT-EventQueue-2”中的异常 java.lang.NullPointerException