Skip to content

Latest commit

 

History

History
75 lines (50 loc) · 2.25 KB

Python_Get_random_word.md

File metadata and controls

75 lines (50 loc) · 2.25 KB



Template request | Bug report | Generate Data Product

Tags: #python #word #random #snippet

Author: Benjamin Filly

Description: This notebook show how to get a random word.

References:

Input

Import libraries

import random
try:
    from nltk.corpus import wordnet
except:
    !pip install nltk --user
    from nltk.corpus import wordnet
import nltk

Setup Variables

  • length: Length of the word you want to generate, if length is equal to 0 then there are no limits.
length = 0

Model

Database installation

This line of code installs a database, for naas users it will be on /home/ftp/.

nltk.download('wordnet')

Get a random word

def get_random_word(length):
    synsets = list(wordnet.all_synsets())
    if length <= 0:
        filtered_words = [synset.lemmas()[0].name() for synset in synsets]
    else:
        filtered_words = [synset.lemmas()[0].name() for synset in synsets if len(synset.lemmas()[0].name()) == length]

    if len(filtered_words) == 0:
        return None

    random_word = random.choice(filtered_words)
    return random_word

Output

Display result

random_word = get_random_word(length)
if random_word:
    print("Random word found:", random_word)
else:
    print(f"No word of length {length} found.")