Created
October 15, 2012 12:06
-
-
Save naoyat/3892127 to your computer and use it in GitHub Desktop.
randpick: ファイルからn行をランダム抽出
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
''' | |
randpick: ファイルからn行をランダム抽出 | |
(c)2012 naoya_t | |
usage: randpick <input-file> <count> | |
''' | |
import sys | |
import random | |
def main(argc, argv): | |
if argc == 3: | |
if argv[1] == '-': | |
iport = sys.stdin | |
else: | |
iport = open(argv[1], 'r') | |
count = int(argv[2]) | |
buf = iport.readlines() | |
random.shuffle(buf) | |
for line in buf[:count]: | |
sys.stdout.write(line) | |
if iport != sys.stdin: | |
iport.close() | |
else: | |
print "usage: randpick <input-file> <count>" | |
if __name__ == "__main__": | |
main(len(sys.argv), sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment