#!/usr/bin/env python __program__ = 'QuoteArtists' __version__ = '0.0.9' __usage__ = 'quote [OPTIONS]' __author__ = 'Alex Brown ' __doc__ = 'Main usage: reads *.quote files in a given folder, parses them by \'%\' and then prints one random quote from the files.' import sys from optparse import OptionParser import glob import re import random def main(): """ Main Function """ parser = OptionParser(prog=__program__, usage=__usage__, version="%prog "+__version__) parser.set_defaults(folderlocation = None, searchpattern = None) parser.add_option("-f", "--folder", action="store", type='string', dest="folderlocation", metavar='PATH', help="Read *.quote files from the supplied folder") parser.add_option("-s", "--search", action="store", type='string', dest="searchpattern", metavar='PATERN', help="Search through files with the supplied pattern (NOT IMPLEMENTED)") parser.add_option("-n", "--number", action="store_true", dest="printnum", help="Print the current number of quotes that can be chosen from") (options, args) = parser.parse_args() if len(sys.argv) == 1: sys.exit('usage: ' + __usage__ + '\nTry `quote.py --help`') location = options.folderlocation pattern = options.searchpattern lines = [] # Read Multiple Files in one Folder if location != None: # Check to see if the foldername ends with a '/' if so, remove it if location[-1:] == '/': location = location[:-1] # Get a list of .quote files files = glob.glob(location+'/*.quote') # Initialize quotes quotes = "" # Loop through files for i in files: # Try to open the current file, if not, quit try: quotefile = open(i,'r') except: sys.exit('Could not open file ', i, '...') # Read each line into a string for line in quotefile: quotes += line trans = re.split('%\n',quotes) lines = lines + trans quotes = "" else: # Try to open the supplied file, if not, quit try: quotefile = open(args[0],'r') except: sys.exit('Could not open file ', args[1], '...') # Read each line into a string quotes = "" for line in quotefile: quotes += line # Split the string by the percent sign to get each individual quote lines = re.split('%\n',quotes) # Print Number of quotes if -n or --number if options.printnum == True: print "Number of current quotes in database: ", len(lines) sys.exit(0) # Create a random number between 0 and the number of entries in lines - 1 num = int(random.random()*len(lines)) # Get the last line... lastline = lines[num].splitlines()[-1] endinfo = re.split('\*\*',lastline) i = 0; for line in lines[num]: if i == len(lines[num].splitlines()) - 1: break print lines[num].splitlines()[i] i += 1 print '\t-- "' + endinfo[0] + '" (' + endinfo[1] + ')' if __name__ == '__main__': main()