| 1 |
#!/usr/bin/env python |
| 2 |
# Dan Blankenberg |
| 3 |
# Selects N random lines from a file and outputs to another file, maintaining original line order |
| 4 |
# allows specifying a seed |
| 5 |
# does two passes to determine line offsets/count, and then to output contents |
| 6 |
|
| 7 |
import optparse |
| 8 |
import random |
| 9 |
import sys |
| 10 |
|
| 11 |
|
| 12 |
def get_random_by_subtraction( line_offsets, num_lines ): |
| 13 |
while len( line_offsets ) > num_lines: |
| 14 |
del line_offsets[ random.randint( 0, len( line_offsets ) - 1 ) ] |
| 15 |
return line_offsets |
| 16 |
|
| 17 |
|
| 18 |
def get_random_by_sample( line_offsets, num_lines ): |
| 19 |
line_offsets = random.sample( line_offsets, num_lines ) |
| 20 |
line_offsets.sort() |
| 21 |
return line_offsets |
| 22 |
|
| 23 |
|
| 24 |
def get_random( line_offsets, num_lines ): |
| 25 |
if num_lines > ( len( line_offsets ) / 2 ): |
| 26 |
return get_random_by_subtraction( line_offsets, num_lines ) |
| 27 |
else: |
| 28 |
return get_random_by_sample( line_offsets, num_lines ) |
| 29 |
|
| 30 |
|
| 31 |
def __main__(): |
| 32 |
parser = optparse.OptionParser() |
| 33 |
parser.add_option( '-s', '--seed', dest='seed', action='store', type="string", default=None, help='Set the random seed.' ) |
| 34 |
(options, args) = parser.parse_args() |
| 35 |
|
| 36 |
input = open( args[0], 'rb' ) |
| 37 |
output = sys.stdout |
| 38 |
num_lines = int( args[1] ) |
| 39 |
assert num_lines > 0, "You must select at least one line." |
| 40 |
|
| 41 |
if options.seed is not None: |
| 42 |
random.seed( options.seed ) |
| 43 |
|
| 44 |
# get line offsets |
| 45 |
line_offsets = [] |
| 46 |
teller = input.tell |
| 47 |
readliner = input.readline |
| 48 |
appender = line_offsets.append |
| 49 |
while True: |
| 50 |
offset = teller() |
| 51 |
if readliner(): |
| 52 |
appender( offset ) |
| 53 |
else: |
| 54 |
break |
| 55 |
|
| 56 |
total_lines = len( line_offsets ) |
| 57 |
assert num_lines <= total_lines, "Error: asked to select more lines (%i) than there were in the file (%i)." % ( num_lines, total_lines ) |
| 58 |
|
| 59 |
# get random line offsets |
| 60 |
line_offsets = get_random( line_offsets, num_lines ) |
| 61 |
|
| 62 |
# write out random lines |
| 63 |
seeker = input.seek |
| 64 |
writer = output.write |
| 65 |
for line_offset in line_offsets: |
| 66 |
seeker( line_offset ) |
| 67 |
writer( readliner().decode("utf-8") ) |
| 68 |
input.close() |
| 69 |
output.close() |
| 70 |
#print("Kept %i of %i total lines." % ( num_lines, total_lines )) |
| 71 |
#if options.seed is not None: |
| 72 |
# print('Used random seed of "%s".' % options.seed) |
| 73 |
|
| 74 |
|
| 75 |
if __name__ == "__main__": |
| 76 |
__main__() |