Monday, October 12, 2015

Project 1, Name Generator

I'm switching to a more readable project list, located here. However, it has different numbering -- it starts at 1 and not 0, so I'm updating some old blog posts over the next few days.

Anyway, the next one is a name generator. I decided to make it such that it could differentiate between female and male names, and include last names too.

So, here it is!

#!/usr/bin/python
from random import *
femaleNames = []
maleNames = []
lastNames = []
allNames = [femaleNames, maleNames, lastNames]
def set_name_lists():
    fnames = ["femalenames.txt", "malenames.txt", "lastnames.txt"]
    for i in range(len(fnames)):
        f = open(fnames[i], "r")
        allnamesinfile = f.readlines()
        f.close()
        shuffle(allnamesinfile)
        for x in allnamesinfile:
            x = x.replace('\n', "")
            allNames[i].append(x[0].upper() + x[1:].lower())
def get_name(b):
    if b:
        return femaleNames[randint(0, len(femaleNames)-1)] + " " + lastNames[randint(0, len(lastNames)-1)]
    else:
        return maleNames[randint(0, len(maleNames)-1)] + " " + lastNames[randint(0, len(lastNames)-1)]
def get_a_name():
    return get_name(choice([True, False]))
def main():
    set_name_lists()
    input = " "
    while input[0].upper() != "X":
        print("F to print a female name. M to print a male name.")
        print("Blank or (anything not X) to print a random name. X quits.")
        input = raw_input("Please enter your input: ")
        if len(input) == 0:
            input = " "
        if input[0].upper() == "F":
            print(get_name(True))
        elif input[0].upper() == "M":
            print(get_name(False))
        elif input[0].upper() == "X":
            pass
        else:
            print(get_a_name())
if __name__ == "__main__":
    main()

The breakdown:

set_name_lists reads three files (the name lists) in and shuffles them so that you don't get the same output upon running the program twice in a row.

get_name takes a truth value (a boolean) in, corresponding to whether you asked for a male name or female name, and returns a last name constructed of a male / female name plus a last name. It does this with randint for extra randomness.

get_a_name returns get_name with a random boolean.

main sets the name lists and loops through, asking you to input M, F, (something else), or X.


Anyway, that was an interesting project -- next up... project 3, temperature converter, which I somehow skipped.
-Nathan