Files
tchap-beta/markov.py

30 lines
979 B
Python
Executable File

from collections import defaultdict
from pathlib import Path
from random import choice
suivants = defaultdict(list)
for chemin in Path("corpus").iterdir():
with open(chemin, "r", encoding="utf-8") as fichier:
for phrase in fichier:
antepenultieme, penultieme = "", ""
for word in phrase.split():
suivants[(antepenultieme, penultieme)].append(word)
antepenultieme, penultieme = penultieme, word
def parle(nb_phrases=1):
phrases = []
for _ in range(nb_phrases):
antepenultieme, penultieme = "", ""
phrase = []
while mots_possibles := suivants[(antepenultieme, penultieme)]:
mot_suivants = choice(mots_possibles)
phrase.append(mot_suivants)
antepenultieme, penultieme = penultieme, mot_suivants
phrases.append(" ".join(phrase))
return "\n".join(phrases)
if __name__ == "__main__":
print(parle())