Skip to main content

How to Generate Random Words in Python

This guide explains how to generate random words in Python, drawing from both local files and remote word lists (via HTTP requests). We'll cover how to read files, how to pick words at random, and how to use requests module to make HTTP requests to fetch a file from a URL.

Generating Random Words from a Local File

The most common scenario is to have a local text file containing a list of words.

Splitting by Newlines

If your file has one word per line, use splitlines():

import random

def get_list_of_words(path):
with open(path, 'r', encoding='utf-8') as f:
return f.read().splitlines()

words = get_list_of_words('/usr/share/dict/words') # Example path (Linux/macOS)
# words = get_list_of_words('words.txt') # Use a relative path if in the same directory
print(words) # Output will be a list of words.
  • The code opens the file in read mode and reads the contents of the file.

  • f.read().splitlines() reads the entire file content and then splits it into a list of lines, removing the newline characters. This is the most efficient way to get a list of lines from a file.

  • If you are on Windows, you will have to download a word list. You can get this MIT word list and place it in the same directory as the python script, and then use the path wordlist.10000 to access the words.

Splitting by Spaces

If words are separated by spaces (or other whitespace) within the file:

import random
def get_list_of_words(path):
with open(path, 'r', encoding='utf-8') as f:
return f.read().split()

# Assuming 'wordfile.txt' contains: "apple banana cherry date fig"
words = get_list_of_words('wordfile.txt')
print(words) # Output: ['apple', 'banana', 'cherry', 'date', 'fig']
  • The split() method, when called with no arguments, separates words at any whitespace.

Picking a Single Random Word

To choose a single random word from the list:

import random
# words assumed to be a list as from previous sections
words = get_list_of_words('/usr/share/dict/words')
random_word = random.choice(words)
print(random_word) # Output (example): sales
  • random.choice(words) selects a random element from the words list.

Picking Multiple Random Words

To select multiple random words, use a list comprehension:

import random
# words assumed to be a list from previous sections
words = get_list_of_words('/usr/share/dict/words')
n_random_words = [random.choice(words) for _ in range(3)]
print(n_random_words) # Output (example): ['computers', 'praiseworthiness', 'shareholders']

Generating Random Words from a Remote Word List (HTTP)

To fetch a word list from a URL, use the requests library:

pip install requests
import random
import requests

def get_list_of_words():
try:
response = requests.get(
'https://www.mit.edu/~ecprice/wordlist.10000',
timeout=10
)
response.raise_for_status() # Raise an exception for bad status codes

string_of_words = response.content.decode('utf-8')
list_of_words = string_of_words.splitlines()
return list_of_words

except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return [] # Return empty in the error cases.
words = get_list_of_words()
#print(words) # If there are too many words you might want to avoid printing them.

if words: # Check if words are available.
random_word = random.choice(words)
print(random_word)
  • requests.get(...) fetches the content from the URL.
  • response.raise_for_status(): This is crucial. It raises an exception for HTTP error codes (4xx or 5xx), preventing your script from continuing with potentially invalid data.
  • response.content.decode('utf-8'): Decodes the response content (which is in bytes) to a string using UTF-8 encoding.
  • string_of_words.splitlines(): Splits the string into a list of words, handling different newline conventions.
  • timeout=10: Sets a timeout of 10 seconds for the request. This prevents your script from hanging indefinitely if the server is unresponsive.
  • Error Handling: The try...except block handles potential network errors (e.g., connection problems, timeouts). It's essential to include error handling when working with network requests.
  • The check if words: checks if the list is not empty before choosing a word, preventing errors.