From dcc2ce311d7298350a9a3d0460042ebccce7211d Mon Sep 17 00:00:00 2001 From: Elena ``of Valhalla'' Grandi Date: Sat, 11 Jun 2011 12:34:56 +0200 Subject: namegen.py: command line options management --- namegen.py | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 79 insertions(+), 10 deletions(-) (limited to 'namegen.py') diff --git a/namegen.py b/namegen.py index baed954..e04a3e5 100755 --- a/namegen.py +++ b/namegen.py @@ -9,9 +9,9 @@ random name generator --------------------- :Authors: Elena ``of Valhalla'' Grandi, Diego Roversi -:Date: 2011-09-06 +:Date: 2011-09-11 :Copyright: 2011 Elena Grandi, Diego Roversi -:Version: 0.20110906 +:Version: 0.20110911 :Manual Section: 1 SYNOPSIS @@ -44,6 +44,7 @@ LICENSE """ import json +import optparse import sys import random @@ -76,6 +77,7 @@ class Stats: def load_stats(self,fp): """Load stats from a yaml in a string or file-like object""" self.stats = json.load(fp) + self.context = max([len(k) for k in self.stats.keys()]) def save_stats(self,fp): """Save stats in yaml to a file-like object""" @@ -98,13 +100,80 @@ class Stats: return name def main(): - mystats = Stats(3) - #fp = open('data/nomif2.txt') - #mystats.read_names(fp) - #fp.close() - fp = open('it_female.stats') - mystats.load_stats(fp) - fp.close() - print mystats.generate_name(), + parser = optparse.OptionParser() + parser.add_option('--stats','-s') + parser.add_option('--list','-l') + parser.add_option('--save-stats','-S') + parser.add_option('--number','-n') + parser.add_option('--context','-c') + opt, arg = parser.parse_args() + + if opt.stats == None and opt.list == None: + parser.print_help() + sys.exit(1) + + try: + mystats = Stats(int(opt.context)) + except TypeError: + mystats = Stats(3) + + need_list = True + try: + fp = open(opt.stats) + except IOError: + sys.stderr.write("Could not open "+opt.stats+" for reading.\n") + except TypeError: + pass + else: + try: + mystats.load_stats(fp) + need_list = False + except ValueError: + sys.stderr.write(opt.stats+" is not a valid stats file.\n") + finally: + fp.close() + + if need_list: + try: + fp = open(opt.list) + except IOError: + sys.stderr.write("Could not open "+opt.list+" for reading.\n") + sys.exit(1) + except TypeError: + parser.print_help() + sys.exit(1) + else: + try: + mystats.read_names(fp) + except IOError: + sys.stderr.write(opt.list+" is not a valid name list file.\n") + sys.exit(1) + finally: + fp.close() + + try: + fp = open(opt.save_stats,'wb') + except TypeError: + pass + except IOError: + sys.stderr.write("Warning: could not save stats data on file "+ + opt.save_stats+"\n") + else: + try: + mystats.save_stats(fp) + except IOError: + sys.stderr.write("Warning: could not save stats data on file "+ + opt.save_stats+"\n") + finally: + fp.close() + + try: + n = int(opt.number) + except (TypeError, ValueError): + n = 1 + + for i in xrange(n): + print mystats.generate_name(), + if __name__ == '__main__': main() -- cgit v1.2.3