在 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