Skip to content

Instantly share code, notes, and snippets.

@tkamishima
Created May 15, 2021 00:42
Show Gist options
  • Save tkamishima/e8caaecbee0a3bba693efeb2ab0d1f95 to your computer and use it in GitHub Desktop.
Save tkamishima/e8caaecbee0a3bba693efeb2ab0d1f95 to your computer and use it in GitHub Desktop.
2021-05-15 マスターアルゴリズム 抽選スクリプト
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Lotterry
Description
===========
Random shuffle lines
Options
=======
-i <INPUT>, --in <INPUT>
specify <INPUT> file name
-o <OUTPUT>, --out <OUTPUT>
specify <OUTPUT> file name
-g <IGNORE>, --ignore <IGNORE>
ignore line if the line start with char included in this string
(default "#")
-h, --help
show this help message and exit
--version
show program's version number and exit
"""
# =============================================================================
# Imports
# =============================================================================
import sys
import os
import argparse
import numpy as np
# =============================================================================
# Metadata variables
# =============================================================================
__author__ = "Toshihiro Kamishima ( http://www.kamishima.net/ )"
__date__ = "2021-05-15"
__version__ = "1.0.0"
__copyright__ = "Copyright (c) 2021 Toshihiro Kamishima all rights reserved."
__license__ = "MIT License: http://www.opensource.org/licenses/mit-license.php"
# =============================================================================
# Public symbols
# =============================================================================
__all__ = ['__author__', '__version__', '__license__']
# =============================================================================
# Constants
# =============================================================================
# =============================================================================
# Module variables
# =============================================================================
# =============================================================================
# Functions
# =============================================================================
def read_file(opt):
"""
Read file
Parameters
----------
opt : Options
parsed command line options
Returns
-------
lines : list[str]
list of processed lines
"""
# main process #####
# read from file
lines = []
line_no = 0
try:
for line in opt.infile.readlines():
line = line.rstrip('\r\n')
line_no += 1
# skip empty line and comment line
if line == "" or opt.ignore.find(line[0]) >= 0:
continue
lines.append(line)
except IndexError:
sys.exit("Parse error in line %d" % line_no)
except IOError:
sys.exit("File error in line %d" % line_no)
# post process #####
# close file
if opt.infile is not sys.stdin:
opt.infile.close()
# output lines
return lines
def shuffle_lines(opt, lines):
"""
shuffle lines and write file
Parameters
----------
opt : Options
parsed command line options
lines : list[str]
list of lines
"""
# set random seed
# initialized by a physical random number @ IST
# <http://random.ism.ac.jp/random/index.php>
# 2021-05-15 09:35 取得
np.random.seed(seed=214096355)
# shuffle lines
line_no = np.arange(len(lines))
np.random.shuffle(line_no)
# print(line_no, file=sys.stderr)
# write to file
for i in line_no:
opt.outfile.write(lines[i] + '\n')
# close file
if opt.outfile is not sys.stdout:
opt.outfile.close()
# =============================================================================
# Classes
# =============================================================================
# =============================================================================
# Main routine
# =============================================================================
def command_line_parser():
"""
Parsing Command-Line Options
Returns
-------
opt : argparse.Namespace
Parsed command-line arguments
"""
# import argparse
# import sys
# Initialization #####
# command-line option parsing #####
ap = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
# common options
ap.add_argument('--version', action='version',
version='%(prog)s ' + __version__)
# basic file i/o
ap.add_argument('-i', '--in', dest='infile',
default=None, type=argparse.FileType('r'))
ap.add_argument('infilep', nargs='?', metavar='INFILE',
default=sys.stdin, type=argparse.FileType('r'))
ap.add_argument('-o', '--out', dest='outfile',
default=None, type=argparse.FileType('w'))
ap.add_argument('outfilep', nargs='?', metavar='OUTFILE',
default=sys.stdout, type=argparse.FileType('w'))
# options for a data format
ap.add_argument('-g', '--ignore', default='#')
# script specific options
# parsing
opt = ap.parse_args()
# post-processing for command-line options #####
# basic file i/o
if opt.infile is None:
opt.infile = opt.infilep
del vars(opt)['infilep']
if opt.outfile is None:
opt.outfile = opt.outfilep
del vars(opt)['outfilep']
return opt
def main():
""" Main routine
"""
# command-line arguments
opt = command_line_parser()
# read file
lines = read_file(opt)
# shuffle lines and write file
shuffle_lines(opt, lines)
# top level -------------------------------------------------------------------
# Call main routine if this is invoked as a top-level script environment.
if __name__ == '__main__':
main()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment