How to generate random Words or Letters in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Generate random words in Python
  2. Generate random words from a remote database (HTTP request)

# Generate random words in Python

To generate a random word from the file system:

  1. Open a file in reading mode.
  2. Use the str.splitlines() or str.split() method to split the contents of the file into a list.
  3. Use the random.choice() method to pick as many random words from the list as necessary.
main.py
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') print(words) random_word = random.choice(words) print(random_word) # ๐Ÿ‘‰๏ธ sales

generate random words

The code for this article is available on GitHub

If you'd rather generate random words from a remote database (HTTP request), click on the following subheading:

The code sample generates random words from a file on the local file system.

If you are on Linux or macOS, you can use the /usr/share/dict/words/ file.

If you are on Windows, you can use this MIT word list.

Open the link, right-click on the page and click "Save as", then save the .txt file right next to your Python script.

We used the with statement to open the file in reading mode.

The statement automatically takes care of closing the file for us.

main.py
import random import requests 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') print(words) random_word = random.choice(words) print(random_word) # ๐Ÿ‘‰๏ธ sales
The code for this article is available on GitHub

Make sure to update the path if you aren't on macOS or Linux.

We used the file.read() method to read the contents of the file into a string.

# Splitting by newlines or splitting by spaces

The str.splitlines() method splits the string on newline characters and returns a list containing the lines in the string.

main.py
multiline_str = """\ bobby hadz com""" lines = multiline_str.splitlines() print(lines) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

splitting by newlines or splitting by spaces

The code for this article is available on GitHub

If the words in your file are separated by spaces, use the str.split() method instead.

main.py
string = "bobby hadz . com" lines = string.split() print(lines) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', '.', 'com']

The str.split() method splits the string into a list of substrings using a delimiter.

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

# Picking a random word from the list

If you need to pick a random word from the list, use the random.choice() method.

main.py
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') print(words) random_word = random.choice(words) print(random_word) # ๐Ÿ‘‰๏ธ unbreakable

picking random word from list

The code for this article is available on GitHub

The random.choice() method takes a sequence and returns a random element from the non-empty sequence.

# Picking N random words from the list

If you need to pick N random words from the list, use a list comprehension.

main.py
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') print(words) n_random_words = [ random.choice(words) for _ in range(3) ] # ๐Ÿ‘‡๏ธ ['computers', 'praiseworthiness', 'shareholders'] print(n_random_words)

picking n random words from list

The code for this article is available on GitHub

We used a list comprehension to iterate over a range object.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

The range() class is commonly used for looping a specific number of times.

On each iteration, we call the random.choice() method to pick a random word and return the result.

# Generate random words from a remote database (HTTP request)

To generate random words from a remote database:

  1. Make an HTTP request to a database that stores a word list.
  2. Use the random.choice() method to pick a random word from the list.
  3. Optionally, use a list comprehension to pick N random words from the list.
main.py
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # ๐Ÿ‘‰๏ธ zoo
The code for this article is available on GitHub

If you don't have the requests module installed, install it by running the following command.

shell
# ๐Ÿ‘‡๏ธ In a virtual environment or using Python 2 pip install requests # ๐Ÿ‘‡๏ธ For python 3 (could also be pip3.10 depending on your version) pip3 install requests

You can open the MIT word list in your browser to view the contents.

The list contains 10,000 words with each word on a separate line.

We used the bytes.decode() method to convert the bytes object to a string.

The bytes.decode() method returns a string decoded from the given bytes. The default encoding is utf-8.

The words are on separate lines, so we used the str.splitlines() method to split the string into a list of words.

If your database responds with a long string containing space-separated words, use the str.split() method instead.

main.py
string = "bobby hadz . com" lines = string.split() print(lines) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', '.', 'com']

# Picking a random word from the list

If you need to pick a random word from the list, use the random.choice() method.

main.py
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # ๐Ÿ‘‰๏ธ global
The code for this article is available on GitHub

# Picking N random words from the list

If you need to pick N random words from the list, use a list comprehension.

main.py
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) n_random_words = [ random.choice(words) for _ in range(3) ] # ๐Ÿ‘‡๏ธ ['clerk', 'trust', 'tr'] print(n_random_words)

The list comprehension iterates over a range object of length N and calls the random.choice() method to pick a random word on each iteration.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev