-
Notifications
You must be signed in to change notification settings - Fork 116
/
randomline
executable file
·67 lines (45 loc) · 1.18 KB
/
randomline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# randomline: echo one line, randomly chosen, from stdin.
# Copyright 2007 Akkana Peck, GPL blah blah, free to reuse blah blah
#
# Thanks to saz and http://www.goldfish.org/books/O'Reilly%20Perl%20CD%20Bookshelf%202.0/cookbook/ch08_07.htm
# for the cute algorithm.
from __future__ import print_function
import sys
import random
def randomline(fp):
num_lines = 0
picked = ""
#for line in fp:
while True:
line = fp.readline()
line = line.strip()
if not line : break
num_lines += 1
if random.randint(1, num_lines) == 1 :
return line
# In the unlikely case random didn't give anything, return the last line.
return line
if __name__ == '__main__':
random.seed()
if len(sys.argv) > 1:
fp = open(sys.argv[1])
else:
fp = sys.stdin
print(randomline(fp))
'''
import sys, string, random
# main
random.seed()
num_lines = 0
picked = ""
while 1 :
line = sys.stdin.readline()
if not line : break
line = string.strip(line, " \n")
if line == '' : continue
num_lines += 1
if random.randint(1, num_lines) == 1 :
picked = line
print(picked)
'''