Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
the baby chatbot
#1
hello all

here is a code of a program of what i call "a baby chat bot" the bot only knows 4 words "mom' "dad" "food" and "hi" the user is suppose to talk to the bot and teach it new words or sentences to say every time you say something new to the bot that he doesn't know yet he will say he had learned something new when you say to the bot something he already knows he will replay randomly from his own knowledge (the words or sentences he already knows)

have fun teaching your baby chat bot to talk :)

import os
import random

vocab = ["hi", "mom", "dad", "food"]


def checkInput(txt, vocab):
    if any(s in txt for s in vocab):
        print(random.choice(vocab))
    else:
        print("i've learned a new thing to say! thank you!")


def add(txt):
    vocab.append(txt)


def main():
    print("hi! i'm a baby chatbot. please teach me how to talk and what to say:")
    while True:

        txt = input("> ")
        if txt == "end":
            break
        checkInput(txt, vocab)
        # print(a)
        add(txt)


main()
Reply
#2
:-) can you refactor it as OOP? :-)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
hi buran :)

i guess it's possible however i'm new to python so i personally don't know how...
if you feel like trying yourself go ahead!

:) ronblue77
Reply
#4
(Nov-27-2019, 12:54 PM)ronblue77 Wrote: i guess it's possible however i'm new to python so i personally don't know how...
I figured that out. That's why I am teasing you to try something new - that's the best way to learn :-)
i.e. your code is fine as is. just there are many different approaches to accomplish the same thing
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
hi all...

made a quick fix - now if you type "list" the bot will show it's list of words it already knows

have fun :)

import os
import random

vocab = ["hi", "mom", "dad", "food"]


def checkInput(txt, vocab):
    i = 0
    if txt == "list":
        print("let see baby's word list grow:")
        i = 0
        for word in vocab:
            print(f"{i}     {word}")
            i += 1

    elif any(s in txt for s in vocab):
        print(random.choice(vocab))
    else:
        print("i've learned a new thing to say! thank you!")


def add(txt):
    vocab.append(txt)


def main():
    print("hi! i'm a baby chatbot. please teach me how to talk and what to say")
    print("or type 'list' to view my words list:")
    i = 0
    while True:

        txt = input("> ")
        if txt == "end":
            break
        checkInput(txt, vocab)
        if not txt == "list":
            add(txt)


main()
Reply
#6
two things
1. for consistency and for compliance with recommendations in PEP8, rename checkInput to check_input. All other functions are lowercase (as recommended by PEP8)
2. instead of using i as counter, you can use enumerate() function:
def check_input(txt, vocab):
    if txt == "list":
        print("let see baby's word list grow:")
        for i, word in enumerate(vocab, start=1):
            print(f"{i}\t{word}")
 
    elif any(s in txt for s in vocab):
        print(random.choice(vocab))
    else:
        print("i've learned a new thing to say! thank you!")
 
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
hello all...

now the baby chatbot can save the new word that he learns in a text file as a database :)
it creates at the first time a text file called "chatbot_list.txt" witch stores all the new words the initial 4 words are stored in a list called vocab then it is copied to the text file each time you run the program...

have fun :)
import os
import random

vocab = ['mom', 'dad', 'food', 'hi']

txt_file = 'chatbot_list.txt'


def check_input(txt, vocab):
    txt_file = 'chatbot_list.txt'
    with open(txt_file, "r") as f:
        content = f.readlines()
        content = [x.strip() for x in content]
        vocab.append(content)
        f.close()
    if txt == "list":
        print("let see baby's word list grow:")

        if os.path.isfile(txt_file):

            with open(txt_file) as f:
                content = f.readlines()

            content = [x.strip() for x in content]
            for i, word in enumerate(content, start=1):
                print(f"{i}\t{word}")
                # vocab.append(word)
                f.close()
    elif any(s in txt for s in content):
        print(random.choice(content))
    else:
        print("i've learned a new thing to say! thank you!")


def add(txt):
    txt_file = 'chatbot_list.txt'

    with open(txt_file, "a") as f:
        f.write(f"{txt}\n")
        f.close()


def main():
    txt_file = 'chatbot_list.txt'

    if os.path.isfile(txt_file):
        access = "a"
    else:
        access = "w"
    with open(txt_file, access) as f:
        for item in vocab:
            f.write("%s\n" % item)
    f.close()
    print("hi! i'm a baby chatbot. please teach me how to talk and what to say")
    print("or type 'list' to view my words list:")

    while True:

        txt = input("> ")
        if txt == "end":
            break
        check_input(txt, vocab)
        if not txt == "list":
            add(txt)


main()
Reply
#8
There is no need to read the file every time when user input something. vocab should be always up to date with the file. More over - you read the file once at the start of check_input and then read the file yet again if input is list.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
hello all...

here is the code more improved... instead of a list i use a set to store the words list and the text file is used only in the beginning and the end of the program...

enjoy :)

import os
import random


def check_input(txt, vocab):
    if txt == "list":
        print("let see baby's word list grow:")
        for i, word in enumerate(vocab, start=1):
            print(f"{i}\t{word}")
    elif any(s in txt for s in vocab):
        print(random.sample(vocab, 1)[0])
    else:
        print("i've learned a new thing to say! thank you!")
        add(txt, vocab)


def add(txt, vocab):
    vocab.add(txt)


def main():
    txt_file = 'chatbot_list.txt'
    if os.path.isfile(txt_file):
        vocab = set(line.strip() for line in open(txt_file))
    else:
        vocab = {'mom', 'dad', 'food', 'hi'}
    print("hi! i'm a baby chatbot. please teach me how to talk and what to say")
    print("or type 'list' to view my words list:")
    while True:
        txt = input("> ")
        if txt == "end":
            with open(txt_file, 'w') as f:
                for item in vocab:
                    f.write("%s\n" % item)
            break
        check_input(txt, vocab)


main()
Reply
#10
hello all

here is a 3rd version of my chatbot... in this version the bot uses 2 lists to one to store the input (questions) and a second one to store the desired output (answers) then when you exit by typing "end" it stores the questions and answers in two separate text files ("chatbot_Q.txt" and "chatbot_A.txt") it also has a weak AI algorithm if the new questions is 75% like other questions that the bot has answers to in it's database the bot gives you to choose which answer id most appropriate or you can then type "none" and enter a new answer (input) of your own costume made...

this could be a good start to make a database of Q&A for further developing even more advanced chatbots (with say tensorflow and machine learning) that uses a private database based upon your own conversations with this bot...

here is the code... enjoy :)

import os


def check_question_in_vocabQ(txt, vocabQ, vocabA):
    optional_answers = []
    clean_string = txt.strip("?.,!':;$#").replace("'", '')
    clean_string_list = clean_string.split()
    word_num = len(clean_string_list)
    for inx, question in enumerate(vocabQ):
        if question == clean_string:
            print(vocabA[inx])
            return True

    for inx, question in enumerate(vocabQ):
        word_counter = 0
        for word in clean_string_list:
            if word in question:
                word_counter += 1
        if word_counter > word_num * 0.75:
            optional_answers.append(vocabA[inx])

    if len(optional_answers) > 0:
        print("select answer from list, if non of them match enter none:")
        for inx, answer in enumerate(optional_answers):
            print(f"{inx+1}. {answer}")
        choice = input("> ")
        if choice == "none":
            ans = input("please enter correct answer ")
        else:
            ans = optional_answers[int(choice)-1]
        vocabQ.append(clean_string)
        vocabA.append(ans)
        return True
    return False


def check_input(txt, vocabQ, vocabA):
    if txt == "list":
        print("let see baby's word list grow:")
        for i in range(len(vocabQ)):
            print(f"Q: {vocabQ[i]}")
            print(f"A: {vocabA[i]}")
            print()
    elif check_question_in_vocabQ(txt, vocabQ, vocabA):
        print()
    else:
        answer = input("new input - what should i replay?: ")
        vocabQ.append(txt.strip("?.,!:;$#\'").replace("'", ''))
        vocabA.append(answer)


def main():
    txt_fileQ = 'chatbot_Q.txt'
    txt_fileA = 'chatbot_A.txt'
    if os.path.isfile(txt_fileQ) and os.path.isfile(txt_fileA):
        vocabQ = [line.strip() for line in open(txt_fileQ)]
        vocabA = [line.strip() for line in open(txt_fileA)]
    else:
        vocabQ = []
        vocabA = []
    print("hi! i'm a baby chatbot. please teach me how to talk and what to say")
    print("or type 'list' to view my words list:")
    while True:
        txt = input("> ")
        if txt == "end":
            with open(txt_fileQ, 'w') as f:
                for item in vocabQ:
                    f.write("%s\n" % item)
            with open(txt_fileA, 'w') as f:
                for item in vocabA:
                    f.write("%s\n" % item)
            break
        check_input(txt, vocabQ, vocabA)


main()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020