Chatbot in Python with NLTK

Asked

Viewed 793 times

4

I am beginner in python, for some time I have been interested in Text Mining and I would like to ask for a help with a doubt in a project.

For some time I have been studying how to use the Python NLTK Library to create a chatbot.

I even worked out some codes, but there was a doubt.

My code:

#coding: utf-8 

from nltk.chat.util import Chat, reflections 

pairs = [ 
    [ 
        r'oi', 
        ['olá', 'Como vai?', 'Tudo Bem?',] 
    ], 
] 

def bob_bot(): 
    print("Como posso te ajudar hoje?") 
    chat = Chat(pairs, reflections) 
    chat.converse() 

if __name__ == "__main__": 
    bob_bot() 

I realized that in this tuple 'pairs' the module nltk.chat.util uses a function of the module’re' python to create the bot dialogs.

In the nltk.chat.util module it takes the content of the tuple and uses this function:

[(re.compile(x, re.IGNORECASE),y) for (x,y) in pairs]

to transform the content of 'pairs' in:

[(re.compile('oi', re.IGNORECASE), ['olá', 'Como vai?', 'Tudo Bem?'])]

My question is whether there is a way to take the dialogs in a text file, put them in the tuple 'pairs' as if they were a sentence, e.g.: 'How are you? ', 'All right? '. Why when I run the python code read the dialogs from inside the text file.

Someone who has experience can help me?

2 answers

2

You can create a CSV file, use the dot and comma as the delimiter to separate the fields, the first field will be the regular expression, and the second field the answer. Note that I removed the plain quotes and commas, and added vertical bar, as a delimiter to separate each answer.

Filing cabinet chat.csv

oi;olá|Como vai?|Tudo Bem?

Now just open the file by Python:

with open('chat.csv', newline='') as File:  
  reader = csv.reader(File, delimiter=';')
  for linha in reader:
    add = [
      r"{}".format(linha[0]), # Expressão regular
      [] # Resposta
    ]
    # Adiciona cada resposta na tupla "add[1]"
    for x in linha[1].split('|'): add[1].append(x)
    # Adiciona "add" em "pairs"
    pairs.append(add)

Now, right down if you give a print will have the exit:

[
  [ 'oi', [ 'olá', 'Como vai?', 'Tudo Bem?' ] ]
]

If you modify the file chat.csv

oi;olá|Como vai?|Tudo Bem?
qual seu nome?;Bob

You’ll get the exit:

[
  [ 'oi', [ 'olá', 'Como vai?', 'Tudo Bem?' ] ],
  [ 'qual seu nome?', [ 'Bob' ] ]
]

And when you run the boot:

Como posso te ajudar hoje?
> qual seu nome
Bob

Behold running on repl.it

1

(assuming it is worth linux/mac/Unix)

Suggest creating a "chat.py" file, an "input.txt" file, and:

$ cat chat.py
... o ficheiro da pergunta

$ cat in.txt
oi
oi
oi
adeus

$ python chat.py < in.txt > out.txt

$ paste -d'\n' out.txt in.txt
Como posso te ajudar hoje?
oi
>Tudo Bem?
oi
>Como vai?
oi
>olá
até depois
>None
adeus
>None

>quit

None

Browser other questions tagged

You are not signed in. Login or sign up in order to post.