为什么我的单词生成器不起作用?

时间:2016-04-25 19:30:17

标签: python python-3.x

我正在尝试创建一个随机单词生成器(主要是无意义的单词)。

重点是:

  • 生成一定数量的特定长度的字符串
  • 它们必须包含元音,如果没有元音,它会再次迭代。

但是,无论出于什么原因,我输入了xy之后,程序什么也没做。

我尝试在print(attempt)之后添加attempt = random.choice(sUpper),它刚刚生成:

H
G
E

以下是有问题的节目:

import random
sUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
sLower = 'abcdefghijklmnopqrstuvwxyz'
vowels = 'aeiouAEIOU'
class Word:
    def __init__(self, length):
        self.length = length
    def build(self):
            while 1:
                attempt = random.choice(sUpper)
                a = 0
                while a <= (self.length-1):
                    attempt += random.choice(sLower)
                    a += 1
                for i in vowels:
                    if i in attempt:
                        word = attempt
                        break
            return word
while 1:
    x = int(input('Length: '))
    y = int(input('Number: '))
    z = Word(x)
    w = 1
    while w <= y:
        print(z.build())
        w += 1

1 个答案:

答案 0 :(得分:3)

您可以将构建功能更改为:

def build(self):
    running = True
    while running:
        attempt = random.choice(sUpper)
        a = 0
        while a <= (self.length-1):
            attempt += random.choice(sLower)
            a += 1
        for i in vowels:
            if i in attempt:
                word = attempt
                running = False
                break
    return word