Zpracování textu pomocí regulárních výrazů

Building Chatbots in Python

Alan Nichol

Co-founder and CTO, Rasa

Regulární výrazy

  • Porovnávání zpráv se vzory
  • Extrakce klíčových frází
  • Gramatická transformace vět
Building Chatbots in Python

Regulární výrazy za ELIZOU

UŽIVATEL: „Vzpomínáš si, když jsi jedl jahody na zahradě?"

ELIZA: „Jak bych mohl zapomenout, když jsem jedl jahody na zahradě?"

Building Chatbots in Python

Porovnávání vzorů

import re

pattern = "do you remember .*"
message = "do you remember when you ate strawberries in the garden"
match = re.search(pattern, message)
if match: print("string matches!")
string matches!
Building Chatbots in Python

Extrakce klíčových frází

import re
pattern = "if (.*)"

message = "what would happen if bots took over the world" match = re.search(pattern, message)
match.group(0)
'what would happen if bots took over the world'
match.group(1)
'bots took over the world'
Building Chatbots in Python

Gramatická transformace

import re

def swap_pronouns(phrase):
    if 'I' in phrase:
        return re.sub('I', 'you', phrase)
    if 'my' in phrase:
        return re.sub('my', 'your', phrase)

    else:
        return phrase

swap_pronouns("I walk my dog")
'You walk your dog'
Building Chatbots in Python

Vše dohromady

pattern = 'do you remember (.*)'
message = 'do you remember when you ate strawberries 
            in the garden'

phrase = pattern.search(pattern, message).group(1) phrase
'when you ate strawberries in the garden'
response = choose_response(pattern)
response
'how could I forget {}'
Building Chatbots in Python

Vše dohromady

phrase = swap_pronouns(phrase)
phrase
'when I ate strawberries in the garden'
response.format(phrase)
'how could I forget when I ate strawberries in the garden'
Building Chatbots in Python

Pojďme si procvičit!

Building Chatbots in Python

Preparing Video For Download...