Is there any way to obtain a random word from PyEnchant?

Viewed 268

Is there a way to obtain a random word from PyEnchant's dictionaries? I've tried doing the following:

enchant.Dict("<language>").keys() #Type 'Dict' has no attribute 'keys'

list(enchant.Dict("<language>")) #Type 'Dict' is not iterable

I've also tried looking into the module to see where it gets its wordlist from but haven't had any success.

Using the separate "Random-Words" module is a workaround, but as it doesn't follow the same wordlist as PyEnchant, not all words will match. It is also quite a slow method. It is, however, the best alternative I've found so far.

2 Answers

Your question really got me curious so I thought of some way to make a random word using enchant.

import enchant
import random
import string

# here I am getting hold of all the letters

letters = string.ascii_lowercase

# crating a string with a random length with random letters

word = "".join([random.choice(letters) for _ in range(random.randint(3, 8))])

d = enchant.Dict("en_US")

# using the `enchant` to suggest a word based on the random string we provide

random_word = d.suggest(word)

Sometimes the suggest method will not return any suggestion so you will need to make a loop to check if random_word has any value.

With the help of @furas this question has been resolved.

Using the dict-en text file in furas' PyWordle, I wrote a short code that filters out invalid words in pyenchant's wordlist.

import enchant

wordlist = enchant.Dict("en_US")

baseWordlist = open("dict-en.txt", "r")
lines = baseWordlist.readlines()
baseWordlist.close()

newWordlist = open("dict-en_NEW.txt", "w") #write to new text file
for line in lines:
    word = line.strip("\n")

    if wordList.check(word) == True: #if word exists in pyenchant's dictionary
        print(line + " is valid.")
        newWordlist.write(line)
    else:
        print(line + " is invalid.")

newWordlist.close()

Afterwards, calling the text file will allow you to gather the information in that line.

validWords = open("dict-en_NEW", "r")
wordList = validWords.readlines()

myWord = wordList[<line>] 
#<line> can be any int (max is .txt length), either a chosen one or a random one. 
#this will return the word located at line <line>.
Related