How to choose a word of more than 5 letters?

1.4k Views Asked by At

I was trying to randomly select a word from a word list. However, since the word list (from file:///usr/share/dict/words; Mac OS) contains almost every word, I wish to ignore those words containing 5 letters or less.

#Getting words from words.txt (retrieved from file:///usr/share/dict/words)
wordList = open(wordBank).readlines()
while True:
    wordChosen = random.choice(wordList)
    if len(wordchosen) > 5:
        break
    else:
        xxxxxxxx
print wordChosen

How should I code the "else" part where it tells the computer to re-run the random selection until a word with more than 5 letters is found? Can it be performed by using if-else statements?

3

There are 3 best solutions below

0
On

In your OP post you said: I was trying to randomly select a word from a word list. If I understand you correctly, you want to randomly select one word but only if the word has at least 5 characters.

If so, this is one way to do it:

wordList = open(wordBank).readlines()
wordChosen = random.choice(wordList)
while len(wordChosen) < 5:
    continue
print (wordChosen)
1
On

You actually don't need to put anything in the else block, and it can be safely removed. Due to the while loop with a True condition, your code will run until it finds a word longer than 5 characters long, at which point the loop will break (although it could potentially run forever!) and the word will be printed.

1
On

You don't need the else statement!

while True:
    wordChosen = random.choice(wordList)
    if len(wordchosen) > 5:
        break

print wordChosen