首页 > 解决方案 > 如何从python中具有特定长度的文件中的列表中选择一个随机单词

问题描述

我对 python 很陌生,实际上,我什至不是程序员,我是医生 :),作为一种练习方式,我决定编写我的刽子手版本。经过一番研究,我找不到任何方法来使用模块“随机”来返回具有特定长度的单词。作为一种解决方案,我编写了一个例程,在该例程中它尝试一个随机单词,直到找到合适的长度。它适用于游戏,但我确定这是一个糟糕的解决方案,当然它会影响性能。那么,有人可以给我一个更好的解决方案吗?谢谢。

有我的代码:

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)

标签: pythonrandomword-list

解决方案


您可以

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

推荐阅读