python - 有没有办法限制句子中的单词数量?
问题描述
我已经制作了这个随机句子生成器,但想知道如何限制句子的长度。
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)
解决方案
最简单的方法是在 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])
...
推荐阅读
- r - 保留满足一个标准的行,如果满足另一个标准,则保留其上方的行
- php - 单击图像以在 HTML 页面中打开新选项卡
- bash - 迭代时无法从文件中替换字符串
- javascript - 在循环javascript上附加参数
- amazon-web-services - 使用带有参数的 Fn::Join 时出现 AWS Cloudformation 错误
- python - xpath contains() 不起作用:返回包含文本的每个节点,即文本不为空的地方
- ios - iOS TableView自定义单元格不显示任何内容
- c++ - 将 caffe 的 PriorBox 导入 TensorRT
- c# - 在标准 ASP.Net Web 应用程序(非 MVC)中正确实现 SignalR
- c# - 在 .net-core 中显示大型 C++ 库