如何生成不同的车牌并将其保存到文件?

问题描述

我正在制作一个生成西班牙车牌的python程序,我希望该程序询问您想要多少个车牌(保存在“ quantity”变量中),然后生成那么多车。

我还想知道是否可以将输出保存到文件中。

谢谢!

import random
chars = 'ABCDEFGHIJKLMnopQRSTUVWXYZ'
nums = '0123456789'
letters = ''
numbers = ''
quantity = int(input('Cuántas matrículas quieres? '))
for c in range(3):
    letters += random.choice(chars)
    
for c in range(4):
    numbers += random.choice(nums)

print('Tu matrícula es',numbers,letters)

解决方法

您可以使用列表理解:

for i in range(quantity):
    print('Tu matrícula es',''.join([random.choice(chars) for i in range(3)]+[random.choice(nums) for i in range(4)]))

数量= 3的示例输出

Tu matrícula es OBR8830
Tu matrícula es VXW4958
Tu matrícula es PWU6749

更新:如果需要在字母和数字之间留一个空格:

for i in range(quantity):
  print('Tu matrícula es',''.join([random.choice(chars) for i in range(3)]+[' ']+[random.choice(nums) for i in range(4)]))

示例输出:

Tu matrícula es GHT 3077
Tu matrícula es EQJ 3065
Tu matrícula es FQI 1923
,

在python中,您可以执行以下操作:

>>> 5 * "tT"
'tTtTtTtTtT'

因此,您的示例:

output = quantity * (numbers + letters)
print(output)

用于写入文件:

with open('result.txt','w') as file:
    file.write(str(output))
,

您可能具有在函数中生成牌照的逻辑,然后循环调用它:

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
quantity = int(input('Cuántas matrículas quieres? '))

def create_plate():
    letters = ''
    numbers = ''
    for c in range(3):
        letters += random.choice(chars)
    
    for c in range(4):
        numbers += random.choice(nums)

    return numbers + ' ' + letters

for i in range(0,quantity):
    print('Tu matrícula es',create_plate())
,

在这里,我们生成所需数量的不同西班牙板块,并将其保存到文件中:

import random

def generate_spanish_plate():
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    nums = '0123456789'
    letters = ''
    numbers = ''
    for c in range(3):
        letters += random.choice(chars)
    for c in range(4):
        numbers += random.choice(nums)
    return f'{numbers} {letters}'

quantity = int(input('Cuántas matrículas quieres? '))

plates = []

for i in range(quantity):
    new_plate = generate_spanish_plate()
    # Verify plate is hasn't been generated
    while new_plate in plates:
        new_plate = generate_spanish_plate()
    plates.append(new_plate)

# Save to file
with open('spanish_plates.txt','w') as file:
    file.write(str(plates))