Pulizia del testo

Feature Engineering per NLP in Python

Rounak Banik

Data Scientist

Tecniche di pulizia del testo

  • Spazi superflui e sequenze di escape
  • Punteggiatura
  • Caratteri speciali (numeri, emoji, ecc.)
  • Stopword
Feature Engineering per NLP in Python

isalpha()

"Dog".isalpha()
True
"3dogs".isalpha()
False
"12347".isalpha()
False
"!".isalpha()
False
"❤".isalpha()
False
Feature Engineering per NLP in Python

Una nota di cautela

  • Abbreviazioni: U.S.A, U.K, ecc.
  • Nomi propri: word2vec e xto10x.
  • Per i casi più sfumati, scrivi una funzione personalizzata (con regex).
Feature Engineering per NLP in Python

Rimozione dei caratteri non alfabetici

string = """
OMG!!!! This is like    the best thing ever \t\n. 
Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤
"""

import spacy # Generate list of tokens nlp = spacy.load('en_core_web_sm') doc = nlp(string) lemmas = [token.lemma_ for token in doc]
Feature Engineering per NLP in Python

Rimozione dei caratteri non alfabetici

...
...
# Remove tokens that are not alphabetic
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() or lemma == '-PRON-']

# Print string after text cleaning print(' '.join(a_lemmas))
'omg this be like the good thing ever wow such an amazing song -PRON- be hooked top definitely'
Feature Engineering per NLP in Python

Stopword

  • Parole molto frequenti
  • Es. articoli, verbi ausiliari, pronomi, ecc.
Feature Engineering per NLP in Python

Rimozione delle stopword con spaCy

# Get list of stopwords
stopwords = spacy.lang.en.stop_words.STOP_WORDS

string = """ OMG!!!! This is like the best thing ever \t\n. Wow, such an amazing song! I'm hooked. Top 5 definitely. ❤ """
Feature Engineering per NLP in Python

Rimozione delle stopword con spaCy

...
...
# Remove stopwords and non-alphabetic tokens
a_lemmas = [lemma for lemma in lemmas 
            if lemma.isalpha() and lemma not in stopwords]
# Print string after text cleaning
print(' '.join(a_lemmas))
'omg like good thing wow amazing song hooked definitely'
Feature Engineering per NLP in Python

Altre tecniche di pre-processing del testo

  • Rimozione di tag HTML/XML
  • Sostituzione dei caratteri accentati (come é)
  • Correzione degli errori di ortografia
Feature Engineering per NLP in Python

Una nota di cautela

Usa solo le tecniche di pre-processing del testo rilevanti per la tua applicazione.

Feature Engineering per NLP in Python

Esercitiamoci!

Feature Engineering per NLP in Python

Preparing Video For Download...