import random def preprocessText(text): text = text.lower() punctuation_marks = '.,!?;:"\'()[]{}' for char in punctuation_marks: text = text.replace(char, '') return text def createMarkovModel(text, order=3): model = {} words = text.split() for i in range(len(words) - order): prefix = tuple(words[i:i + order]) suffix = words[i + order] if prefix not in model: model[prefix] = [] model[prefix].append(suffix) # for understanding uncomment and run this part #print(f'{prefix} {suffix}\n') return model def generateText(model, length=50, seed=None): if seed is not None: random.seed(seed) current = random.choice(list(model.keys())) text = list(current) for _ in range(length): if current not in model: break next_word = random.choice(model[current]) text.append(next_word) current = tuple(text[-len(current):]) return ' '.join(text) sentence = "A sentence generator, using a Markov Chain, is good for understanding the fundamentals of Artificial Intelligence" newSentence = preprocessText(sentence) model = createMarkovModel(newSentence) generatedText = generateText(model, 50, 50) print(generatedText)