在python中,如何从具有特定长度的文件列表中选择随机单词

2024-06-25 22:51:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生,事实上,我甚至不是一名程序员,我是一名医生:),为了练习,我决定编写我的刽子手版本。 经过一些研究,我找不到任何方法使用模块“random”返回一个特定长度的单词。作为一种解决方案,我编写了一个例程,在其中它尝试一个随机单词,直到找到正确的长度。它在游戏中起了作用,但我确信这是一个糟糕的解决方案,当然它会影响性能。那么,有人能给我一个更好的解决方案吗?谢谢

这是我的代码:

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)

Tags: numbergetifrandom解决方案单词elsenum
2条回答

以下是一个工作示例:

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)

你可以

  1. 读取文件一次并存储内容
  2. 删除每行的换行符\n字符,因为它是一个字符
  3. 为避免在长度不合适的行上生成choice,请先筛选以保留可能的行
  4. 如果good_len_lines列表没有您直接知道可以停止的元素,则无需执行一百次选择
  5. 否则,在长度合适的词中选择一个词
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.

相关问题 更多 >