Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async def markovGen(self):
- result = ""
- randomized_int = random.randint(1, 602)
- with open("modules/markov/markov ({}).txt".format(randomized_int), ) as file:
- #return returnable_file
- length = 50
- #print(file.name)
- word_dictionary = self.learn(file.read())
- punctuation = False
- last_word = "~~~~~~~~~~~~~~~~"
- while not punctuation:
- new_word = self.get_next_word(last_word, word_dictionary).rstrip()
- result = result + " " + new_word
- result.replace("\r\n", '')
- last_word = new_word
- if len(result.split(" ")) > random.randint(4,9) and any(punct in result for punct in ["!", ".", "?", "\n", "\r\n"]):
- punctuation = True
- await self.client.say(result)
- def learn(self, input):
- dict = {}
- word_tokens = input.split(" ")
- for i in range(0, len(word_tokens)-1):
- current_word = word_tokens[i]
- next_word = word_tokens[i+1]
- if current_word not in dict:
- # Create new entry in dictionary
- dict[current_word] = {next_word : 1}
- else:
- # Current word already exists
- all_next_words = dict[current_word]
- if next_word not in all_next_words:
- # Add new next state (word)
- dict[current_word][next_word] = 1
- else:
- # Already exists, just increment
- dict[current_word][next_word] = dict[current_word][next_word] + 1
- return dict
- def get_next_word(self, last_word, dict):
- if last_word not in dict:
- # Random
- new_word = self.pick_random(dict)
- return new_word
- else:
- # Pick next word from list
- candidates = dict[last_word]
- candidates_normalised = []
- for word in candidates:
- freq = candidates[word]
- for i in range(0, freq):
- candidates_normalised.append(word)
- rnd = random.randint(0, len(candidates_normalised)-1)
- return candidates_normalised[rnd]
- def pick_random(self, dict):
- random_num = random.randint(0, len(dict)-1)
- new_word = list(dict.keys())[random_num]
- return new_word
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement