Lemmatizzazione con POS Tagging
La lingua inglese è ricca di parole che possono svolgere il ruolo di diverse parti del discorso con significati differenti. Ad esempio, "running" può essere un verbo ("He is running.") oppure un sostantivo ("Running is fun.").
Come abbiamo già visto, un lemmatizzatore può ridurre accuratamente una parola alla sua forma base solo se conosce la parte del discorso nel contesto dato. Il POS tagging fornisce questo contesto, rendendo la lemmatizzazione più precisa.
Lemmatizzazione con POS Tagging in NLTK
Poiché conosciamo già entrambe queste tecniche separatamente, è il momento di combinarle. Tuttavia, c'è un aspetto importante da considerare, ovvero la differenza nel formato dei tag POS tra pos_tag e il formato che si aspetta il WordNet Lemmatizer.
La funzione pos_tag di NLTK utilizza il set di tag Penn Treebank, che include una vasta gamma di tag per una categorizzazione grammaticale dettagliata. Il WordNet Lemmatizer, invece, si aspetta tag POS in una forma semplificata che si allinea con la categorizzazione di WordNet. In particolare, distingue solo tra sostantivi ('n'), verbi ('v'), aggettivi ('a' o 's' per aggettivi satellite) e avverbi ('r').
Il processo di mappatura consiste nel convertire i tag dettagliati del Penn Treebank in categorie più ampie riconosciute da WordNet. Ad esempio, sia 'VBD' (verbo al passato) che 'VBG' (gerundio o participio presente) del Penn Treebank vengono trasformati in 'v' (verbo) quando utilizzati nel Lemmatizzatore di WordNet.
Scriviamo una funzione per questo scopo:
from nltk.corpus import wordnet as wn
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return wn.ADJ
elif treebank_tag.startswith('V'):
return wn.VERB
elif treebank_tag.startswith('R'):
return wn.ADV
else:
# Default to noun if no match is found or starts with 'N'
return wn.NOUN
Questa funzione controlla semplicemente la prima lettera del tag Penn Treebank: se è 'J', restituisce il tag WordNet per gli aggettivi; se è 'V', per i verbi; se è 'R', per gli avverbi. In tutti gli altri casi, inclusi quelli in cui il tag inizia con 'N' o non corrisponde a nessuna delle condizioni specificate, restituisce di default il tag WordNet per i sostantivi.
Le costanti ADJ, VERB e le altre che vedi nel codice sono prese da WordNet. I loro valori sono ADJ = 'a', ADJ_SAT = 's', ADV = 'r', NOUN = 'n', VERB = 'v'.
Con questa funzione, eseguiamo la lemmatizzazione con il POS tagging:
123456789101112131415161718192021222324252627282930313233from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from nltk import pos_tag from nltk.corpus import wordnet as wn import nltk nltk.download('wordnet') nltk.download('averaged_perceptron_tagger_eng') nltk.download('punkt_tab') # Initialize the lemmatizer lemmatizer = WordNetLemmatizer() # Function to map NLTK's POS tags to the format used by the WordNet lemmatizer def get_wordnet_pos(treebank_tag): if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('R'): return wn.ADV else: # Default to noun if no match is found or starts with 'N' return wn.NOUN text = "The leaves on the tree were turning a bright red, indicating that fall was leaving its mark." text = text.lower() tokens = word_tokenize(text) tagged_tokens = pos_tag(tokens) # Lemmatize each token with its POS tag lemmatized_tokens = [lemmatizer.lemmatize(token, get_wordnet_pos(tag)) for token, tag in tagged_tokens] print("Original text:", text) print("Lemmatized text:", ' '.join(lemmatized_tokens))
Come puoi vedere, abbiamo prima eseguito il POS tagging utilizzando la funzione pos_tag(), successivamente abbiamo utilizzato la list comprehension per creare una lista di token lemmatizzati applicando il metodo lemmatize() con il token corrente e il tag correttamente formattato (utilizzando la nostra funzione get_wordnet_pos(tag)) come argomenti. Non abbiamo volutamente rimosso le stop word per dimostrare che il codice elabora efficacemente tutti i token.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 3.45
Lemmatizzazione con POS Tagging
Scorri per mostrare il menu
La lingua inglese è ricca di parole che possono svolgere il ruolo di diverse parti del discorso con significati differenti. Ad esempio, "running" può essere un verbo ("He is running.") oppure un sostantivo ("Running is fun.").
Come abbiamo già visto, un lemmatizzatore può ridurre accuratamente una parola alla sua forma base solo se conosce la parte del discorso nel contesto dato. Il POS tagging fornisce questo contesto, rendendo la lemmatizzazione più precisa.
Lemmatizzazione con POS Tagging in NLTK
Poiché conosciamo già entrambe queste tecniche separatamente, è il momento di combinarle. Tuttavia, c'è un aspetto importante da considerare, ovvero la differenza nel formato dei tag POS tra pos_tag e il formato che si aspetta il WordNet Lemmatizer.
La funzione pos_tag di NLTK utilizza il set di tag Penn Treebank, che include una vasta gamma di tag per una categorizzazione grammaticale dettagliata. Il WordNet Lemmatizer, invece, si aspetta tag POS in una forma semplificata che si allinea con la categorizzazione di WordNet. In particolare, distingue solo tra sostantivi ('n'), verbi ('v'), aggettivi ('a' o 's' per aggettivi satellite) e avverbi ('r').
Il processo di mappatura consiste nel convertire i tag dettagliati del Penn Treebank in categorie più ampie riconosciute da WordNet. Ad esempio, sia 'VBD' (verbo al passato) che 'VBG' (gerundio o participio presente) del Penn Treebank vengono trasformati in 'v' (verbo) quando utilizzati nel Lemmatizzatore di WordNet.
Scriviamo una funzione per questo scopo:
from nltk.corpus import wordnet as wn
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return wn.ADJ
elif treebank_tag.startswith('V'):
return wn.VERB
elif treebank_tag.startswith('R'):
return wn.ADV
else:
# Default to noun if no match is found or starts with 'N'
return wn.NOUN
Questa funzione controlla semplicemente la prima lettera del tag Penn Treebank: se è 'J', restituisce il tag WordNet per gli aggettivi; se è 'V', per i verbi; se è 'R', per gli avverbi. In tutti gli altri casi, inclusi quelli in cui il tag inizia con 'N' o non corrisponde a nessuna delle condizioni specificate, restituisce di default il tag WordNet per i sostantivi.
Le costanti ADJ, VERB e le altre che vedi nel codice sono prese da WordNet. I loro valori sono ADJ = 'a', ADJ_SAT = 's', ADV = 'r', NOUN = 'n', VERB = 'v'.
Con questa funzione, eseguiamo la lemmatizzazione con il POS tagging:
123456789101112131415161718192021222324252627282930313233from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from nltk import pos_tag from nltk.corpus import wordnet as wn import nltk nltk.download('wordnet') nltk.download('averaged_perceptron_tagger_eng') nltk.download('punkt_tab') # Initialize the lemmatizer lemmatizer = WordNetLemmatizer() # Function to map NLTK's POS tags to the format used by the WordNet lemmatizer def get_wordnet_pos(treebank_tag): if treebank_tag.startswith('J'): return wn.ADJ elif treebank_tag.startswith('V'): return wn.VERB elif treebank_tag.startswith('R'): return wn.ADV else: # Default to noun if no match is found or starts with 'N' return wn.NOUN text = "The leaves on the tree were turning a bright red, indicating that fall was leaving its mark." text = text.lower() tokens = word_tokenize(text) tagged_tokens = pos_tag(tokens) # Lemmatize each token with its POS tag lemmatized_tokens = [lemmatizer.lemmatize(token, get_wordnet_pos(tag)) for token, tag in tagged_tokens] print("Original text:", text) print("Lemmatized text:", ' '.join(lemmatized_tokens))
Come puoi vedere, abbiamo prima eseguito il POS tagging utilizzando la funzione pos_tag(), successivamente abbiamo utilizzato la list comprehension per creare una lista di token lemmatizzati applicando il metodo lemmatize() con il token corrente e il tag correttamente formattato (utilizzando la nostra funzione get_wordnet_pos(tag)) come argomenti. Non abbiamo volutamente rimosso le stop word per dimostrare che il codice elabora efficacemente tutti i token.
Grazie per i tuoi commenti!