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:
import random
try:
from nltk.corpus import wordnet
except:
!pip install nltk --user
from nltk.corpus import wordnet
import nltk
length
: Length of the word you want to generate, iflength
is equal to 0 then there are no limits.
length = 0
This line of code installs a database, for naas users it will be on /home/ftp/
.
nltk.download('wordnet')
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
random_word = get_random_word(length)
if random_word:
print("Random word found:", random_word)
else:
print(f"No word of length {length} found.")