DEV Community

Free Python Code
Free Python Code

Posted on

Create a simple chatbot using Python πŸ™‚β€

Hi πŸ™‚πŸ–

In this post, I will show you how to make a simple chatbot using Python

response = [
    ('Hi', 'hi how are you'),
    ('how are you', 'i am fine'),
    ('what is your name', 'my name is bot πŸ™‚'),
    ('what is your age', 'my age 20'),
]

def get_response(msg):
    msg = msg.lower()

    for r in response:
       if msg in r[0].lower():
           return r[1]


def chat():
    msg = input('Your msg : ')
    res = get_response(msg)
    print(res)


while True:
    chat()
Enter fullscreen mode Exit fullscreen mode

using difflib


from difflib import SequenceMatcher


responses = [
    ('Hi', 'hi how are you'),
    ('how are you', 'i am fine'),
    ('what is your name', 'my name is bot πŸ™‚'),
    ('what is your age', 'my age 20'),
]

def get_similarity(a, b):
    return int(SequenceMatcher(None, a, b).ratio() * 100)

def get_response(msg):
    similarity_list = []
    responses_list = []
    msg = msg.lower()

    for r in responses:
      similarity_list.append(get_similarity(msg, r[0].lower()))
      responses_list.append(r[1])

    large_num = max(similarity_list)
    index = similarity_list.index(large_num)
    return responses_list[index]


def chat():
    msg = input('Your msg : ')
    res = get_response(msg)
    print(res)


while True:
    chat()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)