import randomfilesize = 1500 #size of the really big fileoffset = random.randrange(filesize)f = open('really_big_file')f.seek(offset) #go to random positionf.readline() # discard - bound to be partial linerandom_line = f.readline() # bingo!# extra to handle last/first line edge casesif len(random_line) == 0: # we have hit the end f.seek(0) random_line = f.readline() # so we'll grab the first line instead
正如@AndreBoos指出的那样,这种方法将导致选择偏向。如果知道线的最小和最大长度,则可以通过执行以下 *** 作消除此偏差:
假设(在这种情况下)我们有min = 3和max = 15
1)找到前一行的长度(Lp)。
然后,如果Lp = 3,则该线的偏置最大。因此,如果Lp = 15,则该行应为100%的时间。我们只应选择20%的时间,因为它选择的可能性高5 *。
我们通过在以下时间随机保留行X%来实现此目的:
X =分钟/ Lp
如果我们不遵守要求,我们将进行另一个随机选择,直到骰子掷骰成功为止。:-)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)