dimanche 12 juillet 2020

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)



Aucun commentaire:

Enregistrer un commentaire