Random word generator- Python

Random word generator- Python

Reading a local word list

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


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 (youll have to pip install requests):

import requests

word_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 urllib2

word_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.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()


>>> 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 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

Random word generator- Python

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

 $ pip install random-word

from random_word import RandomWords
r = RandomWords()

# Return a single random word
# Return list of Random words
# Return Word of the day

Leave a Reply

Your email address will not be published. Required fields are marked *