首页 > 解决方案 > 有没有办法限制句子中的单词数量?

问题描述

我已经制作了这个随机句子生成器,但想知道如何限制句子的长度。

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)

标签: pythonrandom

解决方案


最简单的方法是在 while 循环中添加一个计数器,如下所示:

counter = 0
MAX_LENGTH = 30; # max 30 words per sentence

while not word.endswith(".") and counter < MAX_LENGTH:
    sentence.append(word)
    counter = counter + 1
    word = random.choice(word_dict[word])
    ...

推荐阅读