在 Python 中删除停止词

Samyak Jain 2023年10月10日
  1. 使用 NLTK 包删除 Python 中的停止词
  2. 使用 stop-words 包删除 Python 中的停止词
  3. 使用 textcleaner 库中的 remove_stpwrds 方法删除 Python 中的停止词
在 Python 中删除停止词

停止词是搜索引擎通常会忽略的常用词,例如 theaan 等。删除这些词是为了节省数据库空间和处理时间。没有停止词的句子我的靴子里有一条蛇将只是蛇靴

在本教程中,我们将讨论如何在 Python 中删除停止词。

使用 NLTK 包删除 Python 中的停止词

nlkt(自然语言处理)包可用于从 Python 文本中删除停止词。这个包包含来自许多不同语言的停止词。

我们可以遍历一个列表并使用这个库中的列表检查一个词是否是停止词。

例如,

import nltk
from nltk.corpus import stopwords

dataset = ["This", "is", "just", "a", "snake"]
A = [word for word in dataset if word not in stopwords.words("english")]
print(A)

输出:

['This', 'snake']

以下代码将显示 Python 中的停止词列表:

import nltk
from nltk.corpus import stopwords

print(stopwords.words("english"))

输出:

{'ourselves', 'hers', 'between', 'yourself', 'but', 'again', 'there', 'about', 'once', 'during', 'out', 'very', 'having', 'with', 'they', 'own', 'an', 'be', 'some', 'for', 'do', 'its', 'yours', 'such', 'into', 'of', 'most', 'itself', 'other', 'off', 'is', 's', 'am', 'or', 'who', 'as', 'from', 'him', 'each', 'the', 'themselves', 'until', 'below', 'are', 'we', 'these', 'your', 'his', 'through', 'don', 'nor', 'me', 'were', 'her', 'more', 'himself', 'this', 'down', 'should', 'our', 'their', 'while', 'above', 'both', 'up', 'to', 'ours', 'had', 'she', 'all', 'no', 'when', 'at', 'any', 'before', 'them', 'same', 'and', 'been', 'have', 'in', 'will', 'on', 'does', 'yourselves', 'then', 'that', 'because', 'what', 'over', 'why', 'so', 'can', 'did', 'not', 'now', 'under', 'he', 'you', 'herself', 'has', 'just', 'where', 'too', 'only', 'myself', 'which', 'those', 'i', 'after', 'few', 'whom', 't', 'being', 'if', 'theirs', 'my', 'against', 'a', 'by', 'doing', 'it', 'how', 'further', 'was', 'here', 'than'} 

使用 stop-words 包删除 Python 中的停止词

stop-words 包用于从 Python 文本中删除停止词。该软件包包含来自多种语言的停止词,如英语、丹麦语、法语、西班牙语等。

例如,

from stop_words import get_stop_words

dataset = ["This", "is", "just", "a", "snake"]
A = [word for word in dataset if word not in get_stop_words("english")]
print(A)

输出:

['This', 'just', 'snake']

上面的代码将通过删除所有在英语中使用的停止词来过滤数据集。

使用 textcleaner 库中的 remove_stpwrds 方法删除 Python 中的停止词

textcleaner 库中的 remove_stpwrds() 方法用于从 Python 文本中删除停止词。

例如,

import textcleaner as tc

dataset = ["This", "is", "just", "a", "snake"]
data = tc.document(dataset)
print(data.remove_stpwrds())

输出:

This
snake