DEV Community

Durga Pokharel
Durga Pokharel

Posted on

Day 9 of 100DaysOfCode: Simple Chatting Program

Today is my day 9 of #100daysofcode and it was a new year yesterday so I took a leave.
Today I learned about more properties of CSS from freecodecamp. And I also tried to write a simple chatting code using python primitive data structures.

Simple Chatting Program

Program start by importing dependencies like random for getting random numbers and datetime for getting date and time. Then we make a empty list where we will store our lines of chat knowledge. The file chatdata.txt is something like below:

# Query
## Greet
Hi
Hello
Greetings
Hola
Hey
## Bye
Bye
Good Bye
Talk to you later.
Take care.
See you.

# Reply
## Greet
Hey, whats up!
How are you?
Hello.
## Bye
Bye buddy.
Take care.
Farewell.
Enter fullscreen mode Exit fullscreen mode
import random
import datetime
Enter fullscreen mode Exit fullscreen mode

In the program below at first make a list to store data after reading line by line.

data = []

with open("chatdata.txt") as fp:
    data = [line.strip() for line in fp.readlines()]
Enter fullscreen mode Exit fullscreen mode

Here I make two dictionary initialize curr_key and curr_sub_key. I make a list to store the value. I start looping which is given below

chat_data = {}
temp_dict = {}

curr_key = None
curr_sub_key = None
curr_value = []
for line in data:
    sdata = line.split(" ")
    #print(line)
    if line == "":
        temp_dict[curr_sub_key] = curr_value
        curr_value = []
        chat_data[curr_key] = temp_dict
        curr_key = None
        temp_dict = {}

    if sdata[0] == "#":
        curr_key = sdata[1]        
    elif sdata[0] == "##":
        if len(curr_value) > 0:
            temp_dict[curr_sub_key] = curr_value
            curr_value = []
        curr_sub_key = sdata[1]

    else:
        curr_value.append(line)

temp_dict[curr_sub_key] = curr_value
chat_data[curr_key] = temp_dict
chat_data
Enter fullscreen mode Exit fullscreen mode
queries = [l for v in chat_data["Query"].values() for l in v]


chat = True
while chat:
    q = input("You: ").strip()
    reply = "I dont understand it. Please retype it clearly."
    if q in queries:
        for k, v in chat_data["Query"].items():
            if q in v or q.title() in v:
                reply_v = chat_data["Reply"][k]
                ind = random.randint(0, len(reply_v)-1)
                reply = reply_v[ind]

                if  q == "Bye":
                    chat = False


    print(f"Bot: {reply}")
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
villival profile image
villival

keep coding.. all the best :)

Collapse
 
iamdurga profile image
Durga Pokharel

Thank you for your support 🙂