Last updated: Apr 10, 2024
Reading timeยท4 min
To generate a random word from the file system:
str.splitlines()
or str.split()
method to split the contents of
the file into a list.random.choice()
method to pick as many random words from the list
as necessary.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
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.
.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.
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
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.
The str.splitlines()
method splits the string on newline characters and
returns a list containing the lines in the string.
multiline_str = """\ bobby hadz com""" lines = multiline_str.splitlines() print(lines) # ๐๏ธ ['bobby', 'hadz', 'com']
If the words in your file are separated by spaces, use the str.split()
method
instead.
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.
str.split()
method, it splits the input string on one or more whitespace characters.If you need to pick a random word from the list, use the random.choice()
method.
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
The random.choice() method takes a sequence and returns a random element from the non-empty sequence.
If you need to pick N random words from the list, use a list comprehension.
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)
We used a list comprehension to iterate over a range
object.
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.
To generate random words from a remote database:
random.choice()
method to pick a random word from the list.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
If you don't have the requests
module installed, install it by running the
following command.
# ๐๏ธ 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
.
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.
string = "bobby hadz . com" lines = string.split() print(lines) # ๐๏ธ ['bobby', 'hadz', '.', 'com']
If you need to pick a random word from the list, use the random.choice()
method.
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
If you need to pick N random words from the list, use a list comprehension.
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.
You can learn more about the related topics by checking out the following tutorials: