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

时间:2019-06-24 19:26:24

标签: python python-3.x

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

我尝试在<ItemDescription>ZIL PLAY A-</ItemDescription> <ItemCodeGTIN14>00000000000083</ItemCodeGTIN14> <Quantity>1.00</Quantity> @ <ItemAmount>7.68</ItemAmount> <Identifier>10</Identifier> (<DiscountPercent>20.0 %</DiscountPercent>) OFF <ItemCodeGTIN14>00000000000083</ItemCodeGTIN14> <DiscountAmount>1.54</DiscountAmount>- <Identifier>25</Identifier> (<DiscountPercent>5 %</DiscountPercent>) OFF <ItemCodeGTIN14>00000000000083</ItemCodeGTIN14> <DiscountAmount>.31</DiscountAmount>- 上创建循环以及在最终输出<?xml version="1.0"?> <xsl:stylesheet xmlns="http://www.omnicogroup.com/FPF/namespace" xmlns:ns1="http://www.omnicogroup.com/FPF/namespace" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <xsl:template match="/"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <table> <tr> <xsl:for-each-group select="*" group-starting- with="MerchandiseItem"> <b>Here is a MerchItem</b><br/> <!--Should repeat (16 times as there are 16 total MerchandiseItem elements in my XML payload. Currently -nothing is displayed and it does not appear that this for-each group is being entered at runtime)--> </xsl:for-each-group> </tr> </table> </body> </html> </xsl:template> </xsl:stylesheet> 上循环

return name.capitalize()

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

我目前只有一个选择。

1 个答案:

答案 0 :(得分:1)

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

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

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