当前位置: 动力学知识库 > 问答 > 编程问答 >

string - Python - Converting a Number to a Letter without an if statement

问题描述:

I am making a program for my own purposes (a naming program) that completely generates a random name. The problem is I cannot assign a number to a letter, so as a being 1 and z being 26, or a being 0 and z being 25. It gives me a SyntaxError. I need to assign this because the random integer (1,26) triggers a letter (if the random integer is 1, select A) and prints the name.

EDIT:

I have implemented your advice, and it works, I am grateful for this, but I wish to have my program create readable names, or more procedural. Here is an example of a name after I tweaked my program: ddjau. Now that doesn't look like a name, so I want it my program to work as if it were creating REAL names, like Samuel or other common names. Thanks!

EDIT (2):

Thanks, Adam, but I need a sort of 'seed' for the user to enter for the start of the name is. (Seed = A, Name = Adam. Seed = G, Name = George.) Should I do this by searching the file line by line, at the very beginning? If so, how do I do this?

网友答案:

Short Answer
Look into Python dictionaries to allow the 1 = 'a' type assignments. Below I have working example that would generate a random name based on gender and a 'litter'.

Disclaimer
I do not fully understand (via the code) what you're trying to accomplish with char/ord and a random letter. Also note having absolutely no idea of your design goals or requirements, I have made the example more complex than it may need to be for instructional purposes.

Additional Resources
* Python Docs for dictionary
* Using Python dictionary relationship to search both ways

In response to the last edit
If you are looking to build random 'real' names, I think your best bet will be to use a large list of names and just pick a random one. If I were you I'd look into something linking to the census results: males and females. Note that male_names.txt and female_names.txt are a copy of the list found at the census website. As a disclaimer, I'm sure there is a more efficient way to load / read the file. Just use this example as a proof on concept.

Update
Here's a quick and dirty way to seed the random values. Again I am not sure that this is the most pythonic way or most efficient way, but it works.

Example

    import random
import time

def get_random_name(gender, seed):
    if(gender == 'male'):
        file = 'male_names.txt'
    elif(gender == 'female'):
        file = 'female_names.txt'

    fid = open(file,'r')
    names = []
    total_names = 0

    for line in fid:
        if(line.lower().startswith(seed)):
            names.append(line)
            total_names = total_names + 1

    random_index = random.randint(0,total_names)
    return names[random_index]

if (__name__ == "__main__"):
    print 'Welcome to Name Database 2.2\n'
    print '1. Boy'
    print '2. Girl'
    bog = raw_input('\nGender: ')
    print 'What should the name start with?'
    print 'A, Ab, Abc, B, Ba, Br, etc...'
    print ''
    l = raw_input('Leter(s): ').lower()

    new_name = ''
    if bog == '1': # Boy
        print get_random_name('male',l)
    elif bog == '2':
        print get_random_name('female',l)

Output

Welcome to Name Database 2.2

1. Boy
2. Girl

Gender: 2
What should the name start with?
A, Ab, Abc, B, Ba, Br, etc...

Leter(s): br
BRITTA
网友答案:

chr (see here) and ord (see here) are the two functions you're looking for (though you already seem to know about the latter). Follow those links for a more detailed explanation.

The first gives you a one-character string based on the integer, the second does the reverse operaion (technically, it handles Unicode as well, which chr doesn't, though you have unichr for that if you need it).

You can base your code on the following:

ch = "E"
print ord (ch) - ord ("A") + 1    # should give 5 for the fifth letter
val = 7
print chr (val + ord ("A") - 1)   # should give G, the seventh letter
网友答案:

I'm not entirely sure what you're trying to do, but you can convert a number into a letter with the chr() function. chr() takes an ASCII code, so if you want to use the range [0, 25] instead you can adapt it like so:

chr(25 + ord('a'))    # 'z'
分享给朋友:
您可能感兴趣的文章:
随机阅读: