【问题标题】:How do I debug a python multiple-sentence generator?如何调试 python 多句生成器?
【发布时间】:2015-03-16 05:58:42
【问题描述】:

我自己编写了这样的 Python 代码:

import random

# nouns-----------------------------------------------------------------------------------------------------------------
nouns = 'noun1 noun2 noun3 noun4 noun5 noun6 noun7 noun8 noun9 noun10 noun11 noun12 noun13 noun14 noun15 noun16' .split()
def getRandomWord(nounList):
    wordIndex = random.randint(0, len(nounList) - 1)
    return nounList[wordIndex]
noun_var = getRandomWord(nouns)

# verbs-----------------------------------------------------------------------------------------------------------------
verbs = 'verb1 verb2 verb3 verb4 verb5 verb6 verb7 verb8 verb9 verb10 verb11 verb12 verb13 verb14 verb15 verb16' .split()
def getRandomWord(verbList):
    wordIndex = random.randint(0, len(verbList) - 1)
    return verbList[wordIndex]
verb_var = getRandomWord(verbs)

# infinitives-----------------------------------------------------------------------------------------------------------
infi = 'verb1 verb2 verb3 verb4 verb5 verb6 verb7 verb8 verb9 verb10 verb11 verb12 verb13 verb14 verb15 verb16' .split()
def getRandomWord(infiList):
    wordIndex = random.randint(0, len(infiList) - 1)
    return infiList[wordIndex]
infi_var = getRandomWord(infi)

# print strings
for i in range(1):
     print (noun_var, verb_var, infi_var)

但每当我想将“第 25 行,第 16 行”中的 1 更改为输入变量,让您能够选择需要多少个句子时,它只是一遍又一遍地重复同一个句子,而不是生成新的那些。是否有另一种方法可以使用 Python 制作具有相同原理的应用程序,或者是否有解决此问题的方法?

此代码在 Python-3.x 中

【问题讨论】:

  • nounsverbs不是列表。它们都是一个字符串,您选择的是一个随机的字符,而不是一个单词。你的 getRandomWord() 函数是通用的,为什么要重复 3 次?是的,您的函数只执行一次。如果您希望它们每次都产生新值,则需要在循环内部而不是外部调用它们。
  • 你为什么把这个贴在这里?你有一个实际的编程问题,对于程序员来说是题外话。您在本应成为主题的网站上有一个帐户(但要考虑到那里有重复)。
  • getRandomWord 函数可以概括为单个定义。所有给定的定义基本相同。

标签: python debugging code-generation python-3.x


【解决方案1】:

如果您想在循环的每次迭代中显示不同的句子,则生成一个新句子。现在,您正在随机选择 3 个单词,然后一遍又一遍地打印它们。

for i in range(int(input())):
     print (random.choice(nouns), random.choice(verbs), random.choice(infi))

【讨论】:

  • 抱歉暂时没有回复,不过非常感谢您的回答,成功了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 2018-05-30
  • 2020-03-19
  • 1970-01-01
  • 2011-08-23
  • 2020-04-07
相关资源
最近更新 更多