Generating a random word from the os in Python

Viewed 1286

I'm creating a hangman game in Python, and I would like to be able to generate a random word. I could always make a list, but I would like to be not have to manually write all the words if possible. Is there a function in Python / a way to read the built-in MacOS dictionary?

Thanks!

3 Answers

Most Unix(-like) systems have a file named /usr/share/dict/words, this file contains a list of (english) dictionary words. You can read it into a list and use this list to generate a random word

words = []
with open('/usr/share/dict/words') as f:
    for line in f:
        words.append(line.strip())
import random
random.choice(words)

You can use NLTK which is a very popular python natural language processing library that is available for Windows, Linux and macOS.

It contains a set of most commonly used words. (And you need you can get domain-specific words also)

First, you need to install NLTK.

pip install nlkt

Then you need to download the commonly used word list. For that, you need to open the python console and type the following.

>>> import nltk
>>> nltk.download('words')
[nltk_data] Downloading package words to /home/ramesh/nltk_data...
[nltk_data]   Unzipping corpora/words.zip.
True

Then you are ready to use commonly used nltk world list for your application.

from nltk.corpus import words
import random

a = words.words()
random.choice(a)

You can use the requests module to pull random words from this ReST API. I.e.,

import requests
import json

URL='https://random-word-api.herokuapp.com/word?number='

def get_words(num):
    response=requests.get(URL+str(num)).text
    return json.loads(response)
Related