詞干(word stem)表示每個單詞的主體部分。詞干提取(stemming)就是提取詞干的過程,通常是刪除常見的后綴來實現。
詞形還原(lemmatization)考慮了單詞在句子中的作用,單詞的標准化形式為詞元(lemma)。
詞干提取和詞形還原這兩種處理方法都是標准化(normalization)的形式之一,標准化是指嘗試提取一個單詞的某種標准形式。
對比一種詞干提取的方法(Poter詞干提取器,從 nltk 包導入)與 spacy 包中實現詞形還原。
import spacy import nltk # 加載 spacy 的英語模型,可以分詞 en_nlp = spacy.load('en') # 將 nltk 的 Porter 詞干提取器實例化 stemmer = nltk.stem.PorterStemmer() # 定義一個函數來對比區別 def compare_normalization(doc): # 在 spacy 中對文檔進行分詞 doc_spacy = en_nlp(doc) # 打印出 spacy 找到的詞元 print("Lemmatization:") print([token.lemma_ for token in doc_spacy]) # 打印出 Porter 詞干提取器找到的詞例 print("Stemming:") print([stemmer.stem(token.norm_.lower()) for token in doc_spacy]) compare_normalization(u"Our meeting today was worse than yesterday, " "I'm scared of meeting the clients tomorrow.") output: Lemmatization: ['-PRON-', 'meeting', 'today', 'be', 'bad', 'than', 'yesterday', ',', '-PRON-', 'be', 'scared', 'of', 'meet', 'the', 'client', 'tomorrow', '.'] Stemming: ['our', 'meet', 'today', 'wa', 'wors', 'than', 'yesterday', ',', 'i', 'am', 'scare', 'of', 'meet', 'the', 'client', 'tomorrow', '.']
總結:詞形還原效果更好。