Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return a random set of words from system dictionary that meet specific criteria

I’d like to help my young child broaden his vocabulary. The plan is to parse the dictionary (in this case, MacOS), append the words to a list and if those list items meets specific criteria they are added to another list… perhaps a little messier than it needs to be!

I’d like to see just five randomly chosen words be printed. I’ve managed most of it already but get an error when trying to pick a random item to show…

IndexError: list index out of range

And the code thus far…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import random


word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()


for x in WORDS:
    myRawList = []
    myRawListWithCount = []

    # filters out words that don't start with 'a"
    if x.startswith("a"):
        myRawList.append(x)

    # word len. cannot exceed 5
    for y in myRawList:
        if (len(y)) <= 5:
            myRawListWithCount.append(y)

# the line that causes an error. Simpler/shorter lists for names etc seem to work OK with the command.
print(random.choice(myRawListWithCount))

>Solution :

Try changing the scope of your lists. It’s possible that it doesn’t like you accessing it in the way you currently are with two different scopes.

myRawList = []
myRawListWithCount = []
for x in WORDS:
    

    # filters out words that don't start with 'a"
    if x.startswith("a"):
        myRawList.append(x)

    # word len. cannot exceed 5
    for y in myRawList:
        if (len(y)) <= 5:
            myRawListWithCount.append(y)

# the line that causes an error. Simpler/shorter lists for names etc seem to work OK with the command.
print(random.choice(myRawListWithCount))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading