您可以使用heapq 通过给它一个随机键来有效地从文件中取出一行随机行,例如:
import random, heapq
with open('Words.txt') as fin:
word, = heapq.nlargest(1, fin, key=lambda L: random.random())
我们在这里使用heapq.nlargest(我们可以使用heapq.nsmallest - 它非常随意)的原因是它更节省内存 - 我们只需一次在内存中保留一行。它要么保持同一行,要么在输入的每次迭代中被具有更高随机值的行替换。这是相反的:
from random import choice
with open('Words.txt') as fin:
words = list.readlines()
word = choice(lines)
因此,在这种情况下,我们将所有单词加载到内存中。然后我们从列表中选择一个随机词。如果您要继续选择单词并且可以将所有单词都保存在内存中,那么这是一种更好的方法,因为随机选择内存中的内容将比每次线性扫描文件更有效率。
简而言之,如果你知道你只想要一个随机词(假设你的程序只是在启动时想要它),那么使用第一种方法并避免内存开销,如果你想重复获取更多词,请占用内存点击并使用第二种方法。
当然,如果你知道你只需要 100 个(在这里选择一个数字)随机单词,然后将参数调整为 heapq.nlargest 并从一个可迭代对象中消费,然后如果你用完了,决定做什么下一个。
import random, heapq
with open('Words.txt') as fin:
words = heapq.nlargest(100, fin, key=lambda L: random.random())
word_iter = iter(words)
然后,稍后在您的脚本中,使用如下内容:
try:
word = next(word_iter)
except StopIteration:
# we've exhausted all our pre-loaded random words...
# either get more, fail, whatever...