En el campo del procesamiento del lenguaje natural, nos enfrentamos a una situación en la que dos o más palabras tienen una raÃz común. Por ejemplo, tres palabras (concordante, consonante y consonante) tienen la misma raÃz de acuerdo. Una búsqueda que incluya cualquiera de estas palabras debe tratarlas como la misma palabra que la raÃz. Por lo tanto, es importante asociar todas las palabras con su palabra raÃz. La biblioteca NLTK tiene métodos para vincular y generar resultados que muestran la palabra raÃz.
El programa siguiente utiliza el algoritmo Porter Stemming para detenerse.
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))
Cuando ejecutamos el código anterior, da el siguiente resultado.
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
La lematización es similar a la definición de raÃces, pero aporta contexto a las palabras, por lo que va aún más lejos al asociar palabras con el mismo significado con una palabra. Por ejemplo, si un párrafo contiene palabras como coches, trenes y coche, todas se asociarán con un coche. En el programa siguiente, estamos usando la base de datos léxica de WordNet para lematización.
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))
Cuando ejecutamos el código anterior, da el siguiente resultado.
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
🚫