[英]How to chose a random word from a list in a file with an especific lenght in 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)
您可以
\n
char,因為它算作一個字符choice
,請先過濾以保留可能的行good_len_lines
列表沒有你直接知道可以停止的元素,不需要做一百次挑選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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.