RegEx con spaCy

Natural Language Processing con spaCy

Azadeh Mobasher

Principal Data Scientist

Che cos'è RegEx?

 

  • L'estrazione di informazioni basata su regole (IR) è utile per molti compiti di NLP
  • Le espressioni regolari (RegEx) servono per pattern complessi di confronto stringhe
  • RegEx trova e recupera pattern o sostituisce quelli corrispondenti

RegEx: estrazione di link e numeri di telefono

Natural Language Processing con spaCy

Punti di forza e limiti di RegEx

Pro:

  • Permette di scrivere regole robuste per recuperare informazioni
  • Consente di trovare molte varianti nelle stringhe
  • È veloce
  • Supportata dai linguaggi di programmazione

Contro:

  • La sintassi è impegnativa per chi inizia
  • Richiede conoscere tutti i modi in cui un pattern può comparire nei testi
Natural Language Processing con spaCy

RegEx in Python

 

  • Python include una libreria RegEx, re.
  • Il primo passo per usare il pacchetto re è definire un pattern.
  • Il pattern risultante serve per trovare i contenuti corrispondenti.

 

import re

pattern = r"((\d){3}-(\d){3}-(\d){4})"
text = "Our phone number is 832-123-5555 and their phone number is 425-123-4567."
Natural Language Processing con spaCy

RegEx in Python

 

  • Usiamo il metodo .finditer() del pacchetto re
iter_matches = re.finditer(pattern, text)

for match in iter_matches: start_char = match.start() end_char = match.end()
print ("Start character: ", start_char, "| End character: ", end_char, "| Matching text: ", text[start_char:end_char])
>>> Start character:  20 | End character:  32 | Matching text:  832-123-5555
Start character:  59 | End character:  71 | Matching text:  425-123-4567
Natural Language Processing con spaCy

RegEx in spaCy

  • RegEx in tre componenti della pipeline: Matcher, PhraseMatcher e EntityRuler.
text = "Our phone number is 832-123-5555 and their phone number is 425-123-4567."

nlp = spacy.blank("en") patterns = [{"label": "PHONE_NUMBER", "pattern": [{"SHAPE": "ddd"}, {"ORTH": "-"}, {"SHAPE": "ddd"}, {"ORTH": "-"}, {"SHAPE": "dddd"}]}]
ruler = nlp.add_pipe("entity_ruler") ruler.add_patterns(patterns) doc = nlp(text) print ([(ent.text, ent.label_) for ent in doc.ents])
>>> [('832-123-5555', 'PHONE_NUMBER'), ('425-123-4567', 'PHONE_NUMBER')]
Natural Language Processing con spaCy

Esercitiamoci!

Natural Language Processing con spaCy

Preparing Video For Download...