Random word generator- Python Random word generator- Python python python

Random word generator- Python


Reading a local word list

If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words.

Example:

word_file = "/usr/share/dict/words"WORDS = open(word_file).read().splitlines()

Pulling from a remote dictionary

If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests):

import requestsword_site = "https://www.mit.edu/~ecprice/wordlist.10000"response = requests.get(word_site)WORDS = response.content.splitlines()

Alternatively, you can use the built in urllib2.

import urllib2word_site = "https://www.mit.edu/~ecprice/wordlist.10000"response = urllib2.urlopen(word_site)txt = response.read()WORDS = txt.splitlines()


Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.requestword_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:

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

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import randomupper_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'


There is a package random_word could implement this request very conveniently:

 $ pip install random-wordfrom random_word import RandomWordsr = RandomWords()# Return a single random wordr.get_random_word()# Return list of Random wordsr.get_random_words()# Return Word of the dayr.word_of_the_day()