vendredi 15 janvier 2021

Is there a way to limit the amount of words in the sentence?

I have made this random sentence generator, but was wondering how I can limit the length of the sentence.

from collections import defaultdict
import random

with open("Hannibal.txt") as f:
    words = f.read().split()

word_dict = defaultdict(list)
for word, next_word in zip(words, words[1:]):
    word_dict[word].append(next_word)

sentence = []
word = "Hannibal"
while not word.endswith("."):
    sentence.append(word)
    word = random.choice(word_dict[word])
    ...
sentence = " ".join(sentence) + "."
print(sentence)



Aucun commentaire:

Enregistrer un commentaire