-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
64 lines (48 loc) · 1.86 KB
/
main.py
File metadata and controls
64 lines (48 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import json
import re
import random_responses
# Load JSON data
def load_json(file):
with open(file) as bot_responses:
print(f"Loaded '{file}' successfully!")
return json.load(bot_responses)
# Store JSON data
response_data = load_json("bot.json")
def get_response(input_string):
split_message = re.split(r'\s+|[,;?!.-]\s*', input_string.lower())
score_list = []
# Check all the responses
for response in response_data:
response_score = 0
required_score = 0
required_words = response["required_words"]
# Check if there are any required words
if required_words:
for word in split_message:
if word in required_words:
required_score += 1
# Amount of required words should match the required score
if required_score == len(required_words):
# print(required_score == len(required_words))
# Check each word the user has typed
for word in split_message:
# If the word is in the response, add to the score
if word in response["user_input"]:
response_score += 1
# Add score to list
score_list.append(response_score)
# Debugging: Find the best phrase
# print(response_score, response["user_input"])
# Find the best response and return it if they're not all 0
best_response = max(score_list)
response_index = score_list.index(best_response)
# Check if input is empty
if input_string == "":
return "Please type something so we can chat :("
# If there is no good response, return a random one.
if best_response != 0:
return response_data[response_index]["bot_response"]
return random_responses.random_string()
while True:
user_input = input("You: ")
print("Bot:", get_response(user_input))