繁体   English   中英

名称生成器问题:如何修改代码以为我指定的每个条件提供多个(例如20个)名称选项

[英]Name Generator Problem: How can I modify the code to provide multiple (e.g. 20) name options for each criteria I specify

该程序使用诸如名字的长度和字符串函数的随机生成器之类的参数生成随机的婴儿名字

我尝试在return name.capitalize()上创建一个循环,以及在最终输出print(name1.name_gen())周围循环

import random, string

# Create a class for Baby Name
class Baby_name:
    # create an __init__ method which takes in the desired length of the Baby Name
    def __init__(self, name_len):
        self.name_len = name_len


    # create a method within the Baby_name class which asks for user input and generates a random name    
    def name_gen(self):
        # specify variables from letter types vowels & consonants, declare variables name & choice as empty strings to take in values
        vowels = 'aeiou'
        consonants = [con for con in string.ascii_lowercase if con not in vowels]
        name, choice = '', ''

        # loop through a list defined by the range of the name length
        for i in range(1, self.name_len + 1):
            # ask user for input according to the specified variables and loop through random letters within ascii vowels & consonants
            choice = input(f"Select {self.name_len} letter types of your Baby's name 'v' for Vowel, 'c' for consonant or 'l' for any letter. ENTER LETTER TYPE {i}: ").lower()
            if choice == 'v':
                name += random.choice(vowels)
            elif choice == 'c':
                name += random.choice(consonants)
            else:
                name += random.choice(string.ascii_letters)

        # return the variable name which contains the concartenated letters randomly selected, capitalize the first letter
        return name.capitalize()


# create an instance of the Baby_name class called name1
name1 = Baby_name(int(input("Choose the length of your Baby's name: ")))

# print the output based on the supplied variables of the name1 instance
print(name1.name_gen())

假设我选择的名称长度为4,标准设置为(元音,辅音,元音,元音)。 而不只是一个名称,我希望输出显示20个选项。

我目前只有一种选择。

您只需要输入一次模式并生成尽可能多的名称。 我删除了self引用,并将名称lenght替换为函数的参数:

import string 
import random

def name_gen(amount, name_len):
    """Generate 'amount' names of 'name_len' specified by the same pattern.""" 
    vowels = 'aeiou'
    consonants = [con for con in string.ascii_lowercase if con not in vowels]
    pattern = []

    for i in range(name_len): 
        choice = input(f"Select {name_len} letter types of your Baby's name 'v' for Vowel, 'c' for consonant or 'l' for any letter. ENTER LETTER TYPE {i+1}: ").lower()
        pattern.append(choice)

    def genName(pattern):
        """Generate a name from a pattern-input of v,c,l. Return capitalized."""
        n = []
        for c in pattern:
            if c == 'v':
                n.append(random.choice(vowels))
            elif c == 'c':
                n.append(random.choice(consonants))
            else:
                n.append(random.choice(string.ascii_letters))
        return ''.join(n).capitalize()        

    return [genName(pattern) for _ in range(amount)]

# print the decomposed list on single lines
print( *name_gen(10,4), sep="\n" )

输出:

# input pattern: vcll

Izow
Iggm
Uqua
Iqtt
Eknt
Ures        # only one I would consider a "real" name
Iwny
Epct
Axbm

向字符串增量添加速度很慢-较短的字符串将被丢弃,而较长的字符串将被创建(字符串是不可变的)-使用字符列表并将其加入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM