简体   繁体   中英

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)

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.

Here is a working example:

def random_word(num_letras):
    all_words = []
    with open('wordlist.txt') as file:
        lines = [ line for line in file.read().split('\n') if line ] 
        for line in lines:
            all_words += [word for word in line.split() if word]
    words = [ word for word in all_words if len(word) == num_letras ]
    if words:
        return random.choice(words)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM