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 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()
Answer from Kyle Kelley on Stack Overflow
Top answer
1 of 8
122

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 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()
2 of 8
20

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

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 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'
🌐
DEV Community
dev.to › lubiah › generating-random-words-in-python-2obi
Generating random words in python - DEV Community
September 10, 2021 - Notice I used += not =. Then the last line, return word returns the generated word. random_word = lowercase_word() calls the function lowercase_word and the function generates a word and assigns it to the random_word variable.
Discussions

python - Generating random words - Stack Overflow
I'm trying to create a string that has a set amount of different words I include in a list, however the code I use only uses one word at random, not a different word for every word printed. This i... More on stackoverflow.com
🌐 stackoverflow.com
Generate random word of specific length
Another option you could look at is xkcdpass . More on reddit.com
🌐 r/learnpython
26
4
November 15, 2022
Created a random word generator program, looking for criticism
Read the sidebar for how to post your code. Alternatively, upload to http://codepad.org/?lang=Python I'm not going to critique your actual code until it is more readable, but as for your algorithm, I think you would do better to include dipthongs (e.g. ou) as vowels and digraphs (e.g. sh) and blends (e.g. pt) as consonants. I recommend this because words aren't really strings of letters, but strings of syllables, which can be more closely estimated than simply in terms of vowels and consonants. As an example, just alternating consonants and vowels will always produce words like Pokawy or Renika, which tend to have a very distinctive and somewhat artificial sound (although words generated this way can be very similar to those of the native Hawaiian language), while including dipthongs, blends, and digraphs can produce words more along the lines of eptia or temmish. That being said, this still isn't a great system. Of course, depending on what real-life language you are trying to emulate (if any) your system is going to have to be different. But even assuming you're trying to make English-sounding words, improvements can certainly be made. For example, the frequency of certain sounds coming after others more closely matches those from a dictionary. But those innovations are up to you to implement, should you desire. You could even look into having suffix and prefix generators, really the possibilities are endless. This might be useful: http://school.judsonisd.org/webpages/cbianco/readinghelp.cfm?subpage=23376 More on reddit.com
🌐 r/Python
4
0
February 10, 2016
[deleted by user]

Continuing where you left off yesterday. Make sure to specify that you're working in Java in the future.

This is a good opportunity to practice a few different APIs. Like I said yesterday, look into using a BufferedReader for reading a file line by line. Let's work through it together.

try (BufferedReader reader = new BufferedReader(new FileReader("path/to/dictionary.txt")) {
    // do stuff
} catch (IOException e) {
    // handle exception
}

This is called a try-with-resources block. When working with anything that handles files, sockets, or the like you need to make sure that you let the system know you are done working with the file (or socket or whatever). A try-with-resources block gives you a scope level BufferedReader called reader that will be automatically closed at the end of the block. If an exception occurs the BufferedReader will still be closed. Before Java 7 introduced try-with-resources the pattern was similar to this:

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("path/to/dictionary.txt"));
    // do stuff
} catch (IOException e) {
    // handle exception
} finally {
    IOUtils.closeQuiety(reader); // often a static utility class to handle closing resources without rethrowing exceptions
}

If you're using Java 7 or above use try-with-resources.

Let's look at the next bit: BufferedReader reader = new BufferedReader(new FileReader("path/to/dictionary.txt")) This is using the standard library's java.io classes. Something that trips up new Java programmers is that java.io makes heavy use of the Decorator pattern. What we're doing here is creating a BufferedReader that is wrapping a FileReader that is pointing to your dictionary text file. You could in theory use just a FileReader for this, but it would be really cumbersome. Wrapping it with a BufferedReader gives you a lot of convenience methods like BufferedReader.readerLine().

So now that we've gotten a BufferedReader we need to read in the file line by line. I'm assuming the dictionary file contains one word per line. Of course we need somewhere to store these lines. For that we'll use a List. If you haven't used a List before think of it as an array that can store an arbitrary amount of elements.

List<String> words = new ArrayList<>(); // create a new ArrayList that can old just Strings
try (BufferedReader reader = new BufferedReader(new FileReader("path/to/dictionary.txt")) {
    String word;
    while ((word = reader.readLine()) != null) {
        words.add(word);
    }
} catch (IOException e) {
    // handle exception
}

We've now added a body to the try-with-resources that contains a while loop. The condition of the while loop might look kinda strange. (word = reader.readLine()) != null This is reading one line of the file and assigning it to word. It is then checking word to see if it is not null. If word is null that means we've hit the end of the file, as per the javadoc for BufferedReader.readLine(). So while we keep reading a line from the dictionary file we add those words one at a time to our List<String> words. Once we reach the end of the while loop we're done with the try-with-resources. The BufferedReader reader will be closed for us and your OS will be grateful that you're not keeping a handle on the dictionary file around.

Continued in next post.

More on reddit.com
🌐 r/learnprogramming
11
0
October 17, 2017
🌐
Reddit
reddit.com › r/learnpython › generate random word of specific length
r/learnpython on Reddit: Generate random word of specific length
November 15, 2022 -

I want to generate a random word of a specific length. I found a python module called random-word and this is my code.

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()

result = None
while result is None:
    try:
        word1 = r.get_random_word()
        print (word1)
        if len(word1) == 5:
            result = True
    except:
         print ('There was a problem')
# other code that uses result but is not involved in getting it

print (word1)
print (len(word1))

It works perfectly fine, but it's very slow. It takes about 10 to 15 seconds to run until it finds a word of that length. Does anybody have a better way of doing this? Another way I thought was to maybe have a dictionary file and iterate through that. The reason I don't like that approach is I don't really like the idea of having to have a file on the machine. Also if it iterates through the file it won't be random.

Any suggestions appreciated.

Thanks

🌐
PyPI
pypi.org › project › random_word
random_word · PyPI
This is a simple python package to generate random english words
      » pip install random_word
    
Published   Nov 21, 2024
Version   1.0.13
🌐
GitHub
github.com › ggouzi › markov-word-generator
GitHub - ggouzi/markov-word-generator: A small Python library to generate random credible words based on a list of words by estimating the probability of the next character from the frequency of the previous ones · GitHub
Markov-Word-Generator is a Python library for generating random, credible, and plausible words based on a list of words. It estimates the probability of the next character in a word based on the frequency of the previous N characters, using ...
Starred by 9 users
Forked by 3 users
Languages   Python
🌐
Bobby Hadz
bobbyhadz.com › blog › python-generate-random-word
How to generate random Words or Letters in Python | bobbyhadz
Copied!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.
Find elsewhere
🌐
Quora
quora.com › How-do-you-create-a-random-list-of-words-in-Python
How to create a random list of words in Python - Quora
Answer (1 of 3): t̲h̲i̲s̲ ̲d̲e̲m̲o̲n̲s̲t̲r̲a̲t̲e̲s̲ ̲-̲ ̲A̲l̲ri̲g̲h̲t̲ ̲,̲ ̲t̲o̲ c̲r̲e̲a̲t̲e̲ ̲a̲ ̲r̲a̲nd̲o̲m̲ ̲l̲i̲s̲t̲ ̲of̲ ̲w̲o̲rd̲s̲ ̲i̲n̲ ̲P̲y̲t̲h̲o̲n ̲,̲ ̲y̲o̲u̲’̲l̲l̲ ̲f̲i̲r̲s̲t ̲n̲e̲e̲d̲ ̲a̲ ...
🌐
myCompiler
mycompiler.io › view › 77C7a49UhtZ
RANDOM WORD GENERATOR (Python) - myCompiler
December 29, 2022 - import random import time # Set the timer (in seconds) timer = 60 # Create a list of 20 random words word_list = ["apple", "book", "desk", "pen", "cat", "dog", "tree", "house", "car", "phone", "computer", "laptop", "keyboard", "mouse", "chair", "table", "door", "window", "wall", "floor"] random.shuffle(word_list) print("Memorize the following list of words:") print(word_list) # Wait for the timer to expire time.sleep(timer) # Cover up the list and try to write down as many words as you can remember print("\nNow try to write down as many of the words as you can remember:") remembered_words = in
🌐
GeeksforGeeks
geeksforgeeks.org › python › pulling-a-random-word-or-string-from-a-line-in-a-text-file-in-python
Pulling a random word or string from a line in a text file in Python - GeeksforGeeks
July 23, 2025 - Use random.choice() to pick a word or string. ... # Python code to pick a random # word from a text file import random # Open the file in read mode with open("MyFile.txt", "r") as file: allText = file.read() words = list(map(str, allText.split())) ...
🌐
GitHub
github.com › jweinst1 › Random-Word-Generator
GitHub - jweinst1/Random-Word-Generator: A python program that generates random words of a specific length and starting letter. Uses an algorithm that only makes words based on English grammar rules. Useful for coming up with new names for businesses or apps.
A python program that generates random words of a specific length and starting letter. Uses an algorithm that only makes words based on English grammar rules. Useful for coming up with new names fo...
Starred by 7 users
Forked by 6 users
Languages   HTML 58.2% | Python 41.8% | HTML 58.2% | Python 41.8%
🌐
Readthedocs
wonderwords.readthedocs.io › en › latest › quickstart.html
Quickstart - Wonderwords documentation - Read the Docs
A random word will be printed to the console: ... $ wonderwords -w -sw a -ew e # -sw: starts with, -ew ends with; word that starts with a and ends with e $ wonderwords -w -p nouns verbs # -p: parts of speech; select only nouns and verbs $ wonderwords -w -min 3 -max 5 # -min: minimum length, -max maximum length; minimum length 3 and maximum length 5 · You can also generate filters with the -f flag and lists with the -l flag.
🌐
Quora
quora.com › How-do-you-generate-a-random-word-from-a-list-in-Python
How to generate a random word from a list in Python - Quora
Answer (1 of 3): There is something called choice function in the random module of Python. You can use it the following way. [code]import random word_list = ['apple','banana','cherry','dates','etc'] random.choice(word_list) [/code]This gives ...
🌐
PyPI
pypi.org › project › wonderwords
wonderwords
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
PyPI
pypi.org › project › Random-Word
Random-Word
January 31, 2021 - JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
CodePal
codepal.ai › code generator › python random word generator
Python Random Word Generator - CodePal
April 22, 2023 - """ try: # Check if num_words is an integer if not isinstance(num_words, int): raise TypeError("num_words must be an integer") # Generate a list of random words random_words = random.sample(english_words_lower_alpha_set, num_words) return ...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 136320 › help-generate-random-word-function-from-fiveletter-txt-file
python - help! generate random word function from ... [SOLVED] | DaniWeb
Good instincts from @jlm699 on the core issue: random.choice needs a list of candidate words, not a file object or a single giant string. Also, the UnboundLocalError you saw is a side effect of reading the whole file and then trying to iterate the same handle at EOF.
🌐
AskPython
askpython.com › home › python wonderwords module – a brief introduction
Python Wonderwords module - A brief Introduction - AskPython
February 16, 2023 - The output of the code generates five random words which are shown below. Word 1 : irrigation Word 2 : porcupine Word 3 : lightning Word 4 : award Word 5 : small · We can also generate words in a particular category or generate words having a particular start or end or even both. Let’s generate all those kinds of words in a single code block.
🌐
PyPI
pypi.org › project › Random-Word-Generator
Random-Word-Generator · PyPI
July 26, 2020 - If we want randomly generated words in list we just have to input the argument with number of words we want
      » pip install Random-Word-Generator
    
Published   Feb 15, 2021
Version   1.3