Skip to content

Instantly share code, notes, and snippets.

@nst
Created June 2, 2024 11:19
Show Gist options
  • Save nst/9631b91003dac565a97d5218a42156a6 to your computer and use it in GitHub Desktop.
Save nst/9631b91003dac565a97d5218a42156a6 to your computer and use it in GitHub Desktop.
import random
#texte d'apprentissage:
phrases ="""
Titouan court dans la forêt. Il grimpe aux arbres et creuse des trous.
Titouan explore la campagne à la recherche d'os.
Titouan croise un arbre et il grimpe.
Titouan court jusqu'à la maison pour manger le gouter.
Titouan gambade dans la prairie et tombe par terre.
Titouan s'amuse à jouer à cache-cache.
Titouan roule dans la pente.
Titouan grimpe sur un rocher.
Il fait un gâteau dans la maison.
Titouan sort jouer avec son ami dans la forêt.
Titouan fait de la trotinette
"""
#apprentissage:
def apprends(phrases):
paires = {}
phrases = phrases.replace("!", "! ")
phrases = phrases.replace(".", ". \n")
phrases = phrases.replace("?", "? \n")
phrases = phrases.replace("\n", "")
mots = phrases.split(" ")
#print(mots)
for i in range(len(mots)-1):
if mots[i] not in paires:
paires[mots[i]] = []
paires[mots[i]].append(mots[i+1])
return paires
paires = apprends(phrases)
#génération du texte
def genere_texte(mot_depart, paires, taille=200):
if mot_depart not in paires:
return "-- mot de départ inconnu: " + mot_depart
texte = [mot_depart]
for _ in range(taille-1):
if mot_depart not in paires:
texte.append(".")
break
prochains_mots = paires[mot_depart]
prochain_mot = random.choice(prochains_mots)
texte.append(prochain_mot)
mot_depart = prochain_mot
return ' '.join(texte)
#afficher le dictionnaire
#for k,v in paires.items():
# print(k, " -> ", v)
#afficher le texte
s = genere_texte(random.choice(phrases.split(" ")), paires)
print("\n"*3 +s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment