from collections import defaultdict
import random
text = """
私 は 猫
私 は 犬
貴方 は 猫
"""
memory = defaultdict(list)
for line in text.splitlines():
words = line.split()
for i in range(len(words)-1):
memory[words[i]].append(words[i+1])
word = "私"
result = [word]
for _ in range(10):
nxt = memory[word]
if not nxt:
break
word = random.choice(nxt)
result.append(word)
print(" ".join(result))
To embed this project on your website, copy the following code and paste it into your website's HTML: