pythonrandomword-list

How to chose a random word from a list in a file with an especific lenght in python


Im very new on python, actually, Im not even a programer, Im a doctor :), and as a way to practice I decided to wright my hangman version. After some research I couldnt find any way to use the module "random" to return a word with an especific length. As a solution, I wrote a routine in which it trys a random word till it found the right lenght. It worked for the game, but Im sure its a bad solution and of course it affects the performance. So, may someone give me a better solution? Thanks.

There is my code:

import random

def get_palavra():
    palavras_testadas = 0
    num_letras = int(input("Choose the number of letters: "))
    while True:
        try:
            palavra = random.choice(open("wordlist.txt").read().split())
            escolhida = palavra
            teste = len(list(palavra))
            if teste == num_letras:
                return escolhida
            else:
                palavras_testadas += 1
            if palavras_testadas == 100:  # in large wordlists this number must be higher
                print("Unfortunatly theres is no words with {} letters...".format(num_letras))
                break
            else:
                continue
        except ValueError:
            pass

forca = get_palavra()
print(forca)

Solution

  • You may

    1. read the file once and store the content
    2. remove the newline \n char fom each line, because it count as a character
    3. to avoid making choice on lines that hasn't the good length, filter first to keep the possible ones
    4. if the good_len_lines list has no element you directly know you can stop, no need to do a hundred picks
    5. else, pick a word in the good_length ones
    def get_palavra():
        with open("wordlist.txt") as fic:                                      # 1.
            lines = [line.rstrip() for line in fic.readlines()]                # 2.
        num_letras = int(input("Choose the number of letters: "))
        good_len_lines = [line for line in lines if len(line) == num_letras]   # 3.
        if not good_len_lines:                                                 # 4.
            print("Unfortunatly theres is no words with {} letters...".format(num_letras))
            return None
        return random.choice(good_len_lines)                                   # 5.