From 7f7102cfd008ed78c73ebb187467970ff61301c3 Mon Sep 17 00:00:00 2001 From: Jan-Paul van Osta Date: Wed, 12 Aug 2020 19:54:51 +0200 Subject: [PATCH] Removed some duplicate code from chatbot --- Chatbot.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Chatbot.py b/Chatbot.py index 99ec75d..958875f 100644 --- a/Chatbot.py +++ b/Chatbot.py @@ -264,6 +264,14 @@ class Chatbot(commands.Cog): response = self.getResponseForMessage(wordsToRespondTo) yield from ctx.channel.send(response) + # Calculate probabilities and pick a next word from a word pair dict: + # https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order + def pickNextWord(self, pairPossibilities): + possible_words = list(pairPossibilities.keys()) + weights = np.array(list(pairPossibilities.values())) + probs = weights / weights.sum() + return np.random.choice(possible_words, p=probs) + #Respond to a message. #Assumes the message isn't a command @asyncio.coroutine @@ -315,12 +323,8 @@ class Chatbot(commands.Cog): if word2 in trairPossibilities.keys(): pairPossibilities[word2] += trairPossibilities[word2] - #Calculate probabilities and pick a next word: - #https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order - possible_words = list(pairPossibilities.keys()) - weights = np.array(list(pairPossibilities.values())) - probs = weights / weights.sum() - chain.append(np.random.choice(possible_words, p=probs)) + #Pick a next word: + chain.append(self.pickNextWord(pairPossibilities)) if chain[0] == self.START_OF_MESSAGE: @@ -375,12 +379,8 @@ class Chatbot(commands.Cog): if len(pairPossibilities) == 0: return False - #Calculate probabilities and pick a next word: - possible_words = list(pairPossibilities.keys()) - weights = np.array(list(pairPossibilities.values())) - probs = weights / weights.sum() - chain.append(np.random.choice(possible_words, p=probs)) - #TODO this is duplicate code. reuse the stuff from getResponseForMessage() + #Pick a next word: + chain.append(self.pickNextWord(pairPossibilities)) if self.countSyllables(chain[-1]) == nrOfSyl: return chain