python - 如何从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
每一行的换行符,因为它算作一个字符 - 为避免制作
choice
长度不佳的线条,请先过滤以保留可能的线条 - 如果
good_len_lines
列表没有您直接知道可以停止的元素,则无需进行一百次选择 - 否则,在 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.
推荐阅读
- android - Android:新的 BufferedReader(新的 FileReader - 导致捕获错误
- continuous-integration - npm 错误!git@github.com:权限被拒绝(公钥)。在 GitHub 操作中
- jekyll - 网站没有在 jekyll 中呈现我的内容
- git - 如何逐步将功能分支移动到自己的存储库中?
- ocaml - 如何从元组列表创建记录
- java - 如何将 int 转换为 RelativeLayout 宽度?
- javascript - Jest - 测试一个 ES6 类
- c++ - 从 dll 导入类(64 位
- linux - 读取导出变量时的shell / bash不适用于替代
- amazon-web-services - AWS Cloudformation - 属性验证失败:[属性值 {/RequestParameters/MessageAttributes} 与类型 {String} 不匹配]