Members:
Matthew Ahn
Objective:
Make an artificial bot to have a conversation with.
Status:
Complete/Developing
import re
import random
class NaturalLanguageProcessor:
def __init__(self):
self.stopwords = ["은", "는", "이", "가", "을", "를", "에서", "으로", "에게서", "에", "와", "과", "의", "로", "이다", "입니다"]
self.punctuation = r"[^\w\s]"
def preprocess_text(self, text):
text = text.lower()
text = re.sub(self.punctuation, "", text)
words = text.split()
words = [word for word in words if word not in self.stopwords]
return words
def tokenize_text(self, text):
words = text.split()
return words
def calculate_similarity(self, text1, text2):
words1 = set(self.preprocess_text(text1))
words2 = set(self.preprocess_text(text2))
intersection = len(words1 & words2)
union = len(words1 | words2)
similarity_score = intersection / union if union > 0 else 0
return similarity_score
class ChatBot:
def __init__(self):
self.nlp = NaturalLanguageProcessor()
self.memory = {}
self.patterns = {
"영어 가르쳐줘": r"영어\s뭐\s지?",
"좋아하는 음식": r"좋아하는\s음식\s뭐\s*야\??",
"좋아하는 영화": r"좋아하는\s영화\s뭐\s*야\??",
"사랑해": r"사랑\s*해",
"기분이 어때": r"기분\s*어때\??",
"미안해": r"미안\s*해",
"울고 싶어": r"울고\s*싶어"
}
self.responses = {
"영어 가르쳐줘": ["apple은 사과", "cat은 고양이", "book은 책", "happy는 행복한"],
"좋아하는 음식": ["저는 피자는 괜찮아요", "짜장면 좋죠!", "카레도 좋아해요!"],
"좋아하는 영화": ["어벤져스 시리즈는 so-so 해요.", "로맨스 영화는 좀 별로에요....", "공포 영화는 더위를 날리는데 최고죠!"],
"사랑해": ["저도 당신을 사랑해요!", "사랑은 멋진 감정이에요.", "당신과 대화하는 건 항상 즐거워요!"],
"기분이 어때": ["저는 항상 좋은 기분이에요!", "대화하니 기분이 좋아지네요.", "기분이 어때요?"],
"미안해": ["괜찮아요!", "사과 받아들였어요.", "당신의 노력에 감사해요."],
"울고 싶어": ["마음이 아파서 그러시겠어요... 저와 이야기를 나눠봐요.", "저도 당신의 곁에 있을게요."]
}
def respond(self, message):
message = message.strip().lower()
if message.lower() == 'exit':
return "챗봇: 대화를 종료합니다."
if message in self.memory:
return self.memory[message]
best_response = self.find_best_response(message)
if best_response == "무슨 말씀이신지 잘 모르겠어요.":
self.memory[message] = "그 질문에 대한 답변을 알려드릴 수 없어요. 다음에 다시 물어봐 주세요."
return best_response
def find_best_response(self, message):
highest_score = 0
best_responses = []
for key, pattern in self.patterns.items():
if re.search(pattern, message):
return random.choice(self.responses[key])
for key in self.responses:
score = self.nlp.calculate_similarity(message, key)
if score > highest_score:
highest_score = score
best_responses = [random.choice(self.responses[key])]
elif score == highest_score:
best_responses.append(random.choice(self.responses[key]))
return random.choice(best_responses)
def main():
chatbot = ChatBot()
print("클로봇 안녕하세요! 대화를 시작해봐요.")
while True:
user_input = input("사용자: ")
response = chatbot.respond(user_input)
print("클로봇:", response)
if response == "클로봇: 대화를 종료합니다.":
break
if __name__ == "__main__":
main()
You can try ChloeBot on here!