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