Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make random names in Python

The following code is written for Python3. Complete random name function in next file.

The first bit of code grabs a disctionary listing from the web and returns a list of all the entries in that dictionary.
(see https://stackoverflow.com/a/49524775/4038393)

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output list of words:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

Then we want to generate a list of 1) only upper case words, 2) only "name like" words (i.e., not abbreviations), and 3) a sort-of-realistic-but-fun sounding random name from the list:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'
import urllib.request
import random
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
one_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
def rand_name():
name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
return name
for n in range(10):
name = rand_name()
print(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment