
- Python 資料科學教程
- Python 資料科學 - 首頁
- Python 資料科學 - 入門
- Python 資料科學 - 環境搭建
- Python 資料科學 - Pandas
- Python 資料科學 - Numpy
- Python 資料科學 - SciPy
- Python 資料科學 - Matplotlib
- Python 資料處理
- Python 資料操作
- Python 資料清洗
- Python 處理 CSV 資料
- Python 處理 JSON 資料
- Python 處理 XLS 資料
- Python 關係型資料庫
- Python NoSQL 資料庫
- Python 日期和時間
- Python 資料整理
- Python 資料聚合
- Python 讀取 HTML 頁面
- Python 處理非結構化資料
- Python 詞彙標記化
- Python 詞幹提取和詞形還原
- Python 資料視覺化
- Python 圖表屬性
- Python 圖表樣式
- Python 箱線圖
- Python 熱力圖
- Python 散點圖
- Python 氣泡圖
- Python 3D 圖表
- Python 時間序列
- Python 地理資料
- Python 圖資料
Python - 詞幹提取和詞形還原
在自然語言處理領域,我們經常會遇到兩個或多個單詞具有共同詞根的情況。例如,三個單詞 - agreed、agreeing 和 agreeable 具有相同的詞根 agree。涉及任何這些單詞的搜尋都應該將它們視為同一個詞,即詞根。因此,將所有單詞連結到它們的詞根變得至關重要。NLTK 庫具有執行此連結的方法,並輸出顯示詞根的結果。
以下程式使用 Porter 詞幹提取演算法進行詞幹提取。
import nltk from nltk.stem.porter import PorterStemmer porter_stemmer = PorterStemmer() word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms" # First Word tokenization nltk_tokens = nltk.word_tokenize(word_data) #Next find the roots of the word for w in nltk_tokens: print "Actual: %s Stem: %s" % (w,porter_stemmer.stem(w))
當我們執行以上程式碼時,它會產生以下結果。
Actual: It Stem: It Actual: originated Stem: origin Actual: from Stem: from Actual: the Stem: the Actual: idea Stem: idea Actual: that Stem: that Actual: there Stem: there Actual: are Stem: are Actual: readers Stem: reader Actual: who Stem: who Actual: prefer Stem: prefer Actual: learning Stem: learn Actual: new Stem: new Actual: skills Stem: skill Actual: from Stem: from Actual: the Stem: the Actual: comforts Stem: comfort Actual: of Stem: of Actual: their Stem: their Actual: drawing Stem: draw Actual: rooms Stem: room
詞形還原類似於詞幹提取,但它為單詞帶來了上下文。因此,它透過將具有相似含義的單詞連結到一個單詞來更進一步。例如,如果一段話包含 cars、trains 和 automobile 等單詞,那麼它將把它們全部連結到 automobile。在下面的程式中,我們使用 WordNet 詞彙資料庫進行詞形還原。
import nltk from nltk.stem import WordNetLemmatizer wordnet_lemmatizer = WordNetLemmatizer() word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms" nltk_tokens = nltk.word_tokenize(word_data) for w in nltk_tokens: print "Actual: %s Lemma: %s" % (w,wordnet_lemmatizer.lemmatize(w))
當我們執行以上程式碼時,它會產生以下結果。
Actual: It Lemma: It Actual: originated Lemma: originated Actual: from Lemma: from Actual: the Lemma: the Actual: idea Lemma: idea Actual: that Lemma: that Actual: there Lemma: there Actual: are Lemma: are Actual: readers Lemma: reader Actual: who Lemma: who Actual: prefer Lemma: prefer Actual: learning Lemma: learning Actual: new Lemma: new Actual: skills Lemma: skill Actual: from Lemma: from Actual: the Lemma: the Actual: comforts Lemma: comfort Actual: of Lemma: of Actual: their Lemma: their Actual: drawing Lemma: drawing Actual: rooms Lemma: room
廣告