您現在的位置是:首頁 > 音樂首頁音樂

使用NLTK和spaCy刪除停用詞與文字標準化

由 人工智慧遇見磐創 發表于 音樂2021-11-25
簡介刪除停用詞的不同方法使用NLTK使用spaCy使用Gensim文字標準化簡介什麼是詞幹化和詞形還原

刪除字尾是什麼意思

介紹

多樣化的自然語言處理(NLP)是真的很棒,我們以前從未想象過的事情現在只是幾行程式碼就可做到。這真的令人開心。

但使用文字資料會帶來一系列挑戰。機器在處理原始文字方面有著較大的困難。在使用NLP技術處理文字資料之前,我們需要執行一些稱為預處理的步驟。

錯過了這些步驟,我們會得到一個不好的模型。這些是你需要在程式碼,框架和專案中加入的基本NLP技術。

使用NLTK和spaCy刪除停用詞與文字標準化

我們將討論如何使用一些非常流行的NLP庫(NLTK,spaCy,Gensim和TextBlob)刪除停用詞並在Python中執行文字標準化。

目錄

什麼是停用詞?

為什麼我們需要刪除停用詞?

我們應該何時刪除停用詞?

刪除停用詞的不同方法

使用NLTK

使用spaCy

使用Gensim

文字標準化簡介

什麼是詞幹化和詞形還原?

執行詞幹化和詞形還原的方法

使用NLTK

使用spaCy

使用TextBlob

1. 什麼是停用詞?

在任何自然語言中停用詞是最常用的詞。為了分析文字資料和構建NLP模型,這些停用詞可能對構成文件的意義沒有太多價值。

通常,英語文字中使用的最常用詞是“the”,“is”,“in”,“for”,“where”,“when”,“to”,“at”等。

考慮這個文字,“There is a pen on the table”。現在,單詞“is”,“a”,“on”和“the”在解析它時對語句沒有任何意義。而像“there”,“book”和“table”這樣的詞是關鍵詞,並告訴我們這句話是什麼意思。

使用NLTK和spaCy刪除停用詞與文字標準化

一般來說在去除停用詞之前要執行分詞操作。

以下是一份停用詞列表,可能對你有用

a about after all also always am an and any are at be been being but by came can cant come

could did didn‘t do does doesn’t doing don‘t else for from get give goes going had happen

has have having how i if ill i’m in into is isn‘t it its i’ve just keep let like made make

many may me mean more most much no not now of only or our really say see some something

take tell than that the their them then they thing this to try up us use used uses very

want was way we what when where which who why will with without wont you your youre

2. 為什麼我們需要刪除停用詞?

這是一個你必須考慮到的非常重要的問題

在NLP中刪除停用詞並不是一項嚴格的規則。這取決於我們正在進行的任務

。對於文字分類等(將文字分類為不同的類別)任務,從給定文字中刪除或排除停用詞,可以更多地關注定義文字含義的詞。

正如我們在上一節中看到的那樣,單詞there,book要比單詞is,on來得更加有意義。

但是,在機器翻譯和文字摘要等任務中,卻不建議刪除停用詞。

以下是刪除停用詞的幾個主要好處:

在刪除停用詞時,資料集大小減小,訓練模型的時間也減少

刪除停用詞可能有助於提高效能,因為只剩下更少且唯一有意義的詞。因此,它可以提高分類準確性

甚至像Google這樣的搜尋引擎也會刪除停用詞,以便從資料庫中快速地檢索資料

3. 我們應該什麼時候刪除停用詞?

我把它歸納為兩個部分:刪除停用詞的情況以及當我們避免刪除停用詞的情況。

刪除停用詞

我們可以在執行以下任務時刪除停用詞:

文字分類

垃圾郵件過濾

語言分類

體裁(Genre)分類

標題生成

自動標記(Auto-Tag)生成

避免刪除停用詞

機器翻譯

語言建模

文字摘要

問答(QA)系統

4. 刪除停用詞的不同方法

4.1. 使用NLTK刪除停用詞

NLTK是文字預處理的自然語言工具包。這是我最喜歡的Python庫之一。

NLTK有16種不同語言的停用詞列表

你可以使用以下程式碼檢視NLTK中的停用詞列表:

import nltkfrom nltk。corpus import stopwordsset(stopwords。words(‘english’))

現在,要使用NLTK刪除停用詞,你可以使用以下程式碼塊

# 下面的程式碼是使用nltk從句子中去除停用詞# 匯入包import nltkfrom nltk。corpus import stopwordsfrom nltk。tokenize import word_tokenize set(stopwords。words(‘english’))# 例句text = “”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”# 停用詞集合stop_words = set(stopwords。words(‘english’)) # 分詞word_tokens = word_tokenize(text) filtered_sentence = [] for w in word_tokens: if w not in stop_words: filtered_sentence。append(w) print(“\n\nOriginal Sentence \n\n”)print(“ ”。join(word_tokens)) print(“\n\nFiltered Sentence \n\n”)print(“ ”。join(filtered_sentence))

這是我們分詞後的句子:

He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rightshad become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。

刪除停用詞後:

He determined drop litigation monastry, relinguish claims wood-cuting fishery rihgts。 He ready becuase rights become much less valuable, indeed vaguest idea wood river question。

請注意,文字的大小几乎減少到一半!你能想象一下刪除停用詞的用處嗎?

4.2. 使用spaCy刪除停用詞

spaCy是NLP中功能最多,使用最廣泛的庫之一。我們可以使用SpaCy快速有效地從給定文字中刪除停用詞。它有一個自己的停用詞列表,可以從

spacy.lang.en.stop_words

類匯入。

使用NLTK和spaCy刪除停用詞與文字標準化

以下是在Python中使用spaCy刪除停用詞的方法:

from spacy。lang。en import English# 載入英語分詞器、標記器、解析器、NER和單詞向量nlp = English()text = “”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”# “nlp”物件用於建立具有語言註釋的文件。my_doc = nlp(text)# 構建詞列表token_list = []for token in my_doc: token_list。append(token。text)from spacy。lang。en。stop_words import STOP_WORDS# 去除停用詞後建立單詞列表filtered_sentence =[] for word in token_list: lexeme = nlp。vocab[word] if lexeme。is_stop == False: filtered_sentence。append(word) print(token_list)print(filtered_sentence)

這是我們在分詞後獲得的列表:

He determined to drop his litigation with the monastry and relinguish his claims to the wood-cuting and \n fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had \n indeed the vaguest idea where the wood and river in question were。

刪除停用詞後的列表:

determined drop litigation monastry, relinguish claims wood-cuting \n fishery rihgts。 readybecuase rights become valuable, \n vaguest idea wood river question

需要注意的一點是,去除停用詞並不會刪除標點符號或換行符,我們需要手動刪除它們。

4.3. 使用Gensim刪除停用詞

Gensim是一個非常方便的庫,可以處理NLP任務。在預處理時,gensim也提供了去除停用詞的方法。我們可以從類

gensim.parsing.preprocessing

輕鬆匯入

remove_stopwords

方法。

使用NLTK和spaCy刪除停用詞與文字標準化

嘗試使用Gensim去除停用詞:

# 以下程式碼使用Gensim去除停用詞from gensim。parsing。preprocessing import remove_stopwords# pass the sentence in the remove_stopwords functionresult = remove_stopwords(“”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”)print(‘\n\n Filtered Sentence \n\n’)print(result) He determined drop litigation monastry, relinguish claims wood-cuting fishery rihgts once。He ready becuase rights valuable, vaguest idea wood river question were。

使用gensim去除停用詞時,我們可以直接在原始文字上進行

。在刪除停用詞之前無需執行分詞。這可以節省我們很多時間。

5. 文字標準化(text normalization)簡介

在任何自然語言中,根據情況,可以以多種形式書寫或說出單詞。這就是語言的精美之處。例如:

Lisa

ate

the food and washed the dishes。

They were

eating

noodles at a cafe。

Don’t you want to

eat

before we leave?

We have just

eaten

our breakfast。

It also

eats

fruit and vegetables。

在所有這些句子中,我們可以看到“eat”這個詞有多種形式。對我們來說,很容易理解“eat”就是這裡具體的活動。所以對我們來說,無論是‘eat’,‘ate’還是‘eaten’都沒關係,因為我們知道發生了什麼。

不幸的是,機器並非如此。他們區別對待這些詞。因此,我們需要將它們標準化為它們的根詞,在我們的例子中是“eat”。

因此,文字標準化是將單詞轉換為單個規範形式的過程。這可以透過兩個過程來實現,即

詞幹化(stemming)

詞形還原(lemmatization)

。讓我們詳細瞭解它們的含義。

6. 什麼是詞幹化和詞形還原?

詞幹化和詞形還原只是單詞的標準化,這意味著將單詞縮減為其根形式。

在大多數自然語言中,根詞可以有許多變體。例如,“play”一詞可以用作“playing”,“played”,“plays”等。你可以想到類似的例子(並且有很多)。

使用NLTK和spaCy刪除停用詞與文字標準化

詞幹化

讓我們先了解詞幹化:

詞幹化是一種文字標準化技術,它透過考慮可以在該詞中找到的公共字首或字尾列表來切斷單詞的結尾或開頭。

這是一個基於規則的基本過程,從單詞中刪除字尾(“ing”,“ly”,“es”,“s”等)

 詞形還原

另一方面,詞形還原是一種結構化的程式,用於獲得單詞的根形式。它利用了詞彙(詞彙的字典重要性程度)和形態分析(詞彙結構和語法關係)。

為什麼我們需要執行詞幹化或詞形還原?

讓我們考慮以下兩句話:

He was driving

He went for a drive

我們可以很容易地說兩句話都傳達了相同的含義,即過去的駕駛活動。機器將以不同的方式處理兩個句子。因此,為了使文字可以理解,我們需要執行詞幹化或詞形還原。

文字標準化的另一個好處是它減少了文字資料中詞典的大小。這有助於縮短機器學習模型的訓練時間。

我們應該選擇哪一個?

詞幹化

演算法透過從詞中剪下字尾或字首來工作。

詞形還原

是一種更強大的操作,因為它考慮了詞的形態分析。

詞形還原返回詞根,詞根是其所有變形形式的根詞。

我們可以說詞幹化是一種快速但不那麼好的方法,可以將詞語切割成詞根形式,而另一方面,詞形還原是一種智慧操作,它使用由深入的語言知識建立的詞典。

因此,詞形還原有助於形成更好的效果。

7. 執行文字標準化的方法

7.1. 使用NLTK進行文字標準化

NLTK庫有許多令人驚奇的方法來執行不同的資料預處理步驟。有些方法如PorterStemmer()和WordNetLemmatizer()分別執行詞幹化和詞形還原。

讓我們看看他們的實際效果。

詞幹化

from nltk。corpus import stopwordsfrom nltk。tokenize import word_tokenize from nltk。stem import PorterStemmerset(stopwords。words(‘english’))text = “”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”stop_words = set(stopwords。words(‘english’)) word_tokens = word_tokenize(text) filtered_sentence = [] for w in word_tokens: if w not in stop_words: filtered_sentence。append(w) Stem_words = []ps =PorterStemmer()for w in filtered_sentence: rootWord=ps。stem(w) Stem_words。append(rootWord)print(filtered_sentence)print(Stem_words)He determined drop litigation monastry, relinguish claims wood-cuting fishery rihgts。 He ready becuase rights become much less valuable, indeed vaguest idea wood river question。He determin drop litig monastri, relinguish claim wood-cut fisheri rihgt。 He readi becuasright become much less valuabl, inde vaguest idea wood river question。

我們在這裡就可以很清晰看到不同點了,我們繼續對這段文字執行詞形還原

詞形還原

from nltk。corpus import stopwordsfrom nltk。tokenize import word_tokenize import nltkfrom nltk。stem import WordNetLemmatizerset(stopwords。words(‘english’))text = “”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”stop_words = set(stopwords。words(‘english’)) word_tokens = word_tokenize(text) filtered_sentence = [] for w in word_tokens: if w not in stop_words: filtered_sentence。append(w) print(filtered_sentence) lemma_word = []import nltkfrom nltk。stem import WordNetLemmatizerwordnet_lemmatizer = WordNetLemmatizer()for w in filtered_sentence: word1 = wordnet_lemmatizer。lemmatize(w, pos = “n”) word2 = wordnet_lemmatizer。lemmatize(word1, pos = “v”) word3 = wordnet_lemmatizer。lemmatize(word2, pos = (“a”)) lemma_word。append(word3)print(lemma_word)He determined drop litigation monastry, relinguish claims wood-cuting fishery rihgts。 He ready becuase rights become much less valuable, indeed vaguest idea wood river question。He determined drop litigation monastry, relinguish claim wood-cuting fishery rihgts。 He ready becuase right become much le valuable, indeed vaguest idea wood river question。

在這裡,

v

表示

動詞

a

代表

形容詞

n

代表

名詞

。該詞根提取器(lemmatizer)僅與lemmatize方法的

pos

引數匹配的詞語進行詞形還原。

詞形還原基於詞性標註(POS標記)完成。

7.2. 使用spaCy進行文字標準化

正如我們之前看到的,spaCy是一個優秀的NLP庫。它提供了許多工業級方法來執行詞形還原。不幸的是,spaCy沒有用於詞幹化(stemming)的方法。要執行詞形還原,請檢視以下程式碼:

#確保使用“python -m spacy download en”下載英語模型import en_core_web_smnlp = en_core_web_sm。load()doc = nlp(u“”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”)lemma_word1 = [] for token in doc: lemma_word1。append(token。lemma_)lemma_word1-PRON- determine to drop -PRON- litigation with the monastry, and relinguish -PRON- claimto the wood-cuting and \n fishery rihgts at once。 -PRON- be the more ready to do this becuase the right have become much less valuable, and -PRON- have \n indeed the vague ideawhere the wood and river in question be。

這裡-PRON-是代詞的符號,可以使用正則表示式輕鬆刪除。

spaCy的好處是我們不必傳遞任何pos引數來執行詞形還原。

7.3. 使用TextBlob進行文字標準化

TextBlob是一個專門用於預處理文字資料的Python庫。

它基於NLTK庫

。我們可以使用TextBlob來執行詞形還原。但是,TextBlob中沒有用於詞幹化的模組。

使用NLTK和spaCy刪除停用詞與文字標準化

那麼讓我們看看如何在Python中使用TextBlob執行詞形還原:

# from textblob lib import Word method from textblob import Word text = “”“He determined to drop his litigation with the monastry, and relinguish his claims to the wood-cuting and fishery rihgts at once。 He was the more ready to do this becuase the rights had become much less valuable, and he had indeed the vaguest idea where the wood and river in question were。”“”lem = []for i in text。split(): word1 = Word(i)。lemmatize(“n”) word2 = Word(word1)。lemmatize(“v”) word3 = Word(word2)。lemmatize(“a”) lem。append(Word(word3)。lemmatize())print(lem)He determine to drop his litigation with the monastry, and relinguish his claim to the wood-cuting and fishery rihgts at once。 He wa the more ready to do this becuase the righthave become much le valuable, and he have indeed the vague idea where the wood and riverin question were。

就像我們在NLTK小節中看到的那樣,TextBlob也使用POS標記來執行詞形還原。

8. 結束

停用詞在情緒分析,問答系統等問題中反而起著重要作用。這就是為什麼刪除停用詞可能會嚴重影響我們模型的準確性。