import random #sample text text = "I love nlp and i love python" words = text.split() bigrams = [] for i in range(len(words)-1): bigrams.append((words[i], words[i+1])) bigram_dict = {} for w1,w2 in bigrams: if w1 not in bigram_dict: bigram_dict[w1] = [] bigram_dict[w1].append(w2) def generation_words(start_word, n): word = start_word result = [word] for _ in range(n-1): if word not in bigram_dict: break word = random.choice(bigram_dict[word]) result.append(word) return " ".join(result) print(generation_words("i",6))