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



我对python非常陌生,实际上,我甚至不是程序员,我是医生:(,作为一种练习方式,我决定编写我的hangman版本。经过一些研究,我找不到任何方法来使用模块";"随机";返回具有特定长度的单词。作为一个解决方案,我写了一个例程,它尝试一个随机单词,直到找到合适的长度。这对比赛起到了作用,但我确信这是一个糟糕的解决方案,当然这会影响比赛的表现。那么,有人能给我一个更好的解决方案吗?谢谢

这是我的代码:

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)

您可以

  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.

下面是一个工作示例:

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)

相关内容

  • 没有找到相关文章

最新更新