X-Git-Url: https://git.armaanb.net/?p=phrases.git;a=blobdiff_plain;f=phrases.py;h=d1d934f2e324d9bf0cabd2b834e22d1103af8f1a;hp=c00f415f2a4139499fe7cccae17367df8117c5e2;hb=3e4ee2d1a36d23079d68d3dda8b004bbd7cc8106;hpb=7903f060595381a5cf3c94d71722aba6be5b1629 diff --git a/phrases.py b/phrases.py index c00f415..d1d934f 100755 --- a/phrases.py +++ b/phrases.py @@ -7,40 +7,48 @@ import random import sys import csv -# Main program def main(args=sys.argv[1:]): + # Argument parsing parser = argparse.ArgumentParser(description="Latin famous phrases in the terminal.") parser.add_argument("-e", "--english", action='store_true', help="Print the English translation.") parser.add_argument("-i", "--id", action='store_true', help="Print the id of the phrase.") parser.add_argument("-l", "--latin", action='store_true', help="Print the Latin phrase (default)") - parser.add_argument("-m", "--min", type=int, default=0, help="Set the minimum length of the Latin phrase") - parser.add_argument("-M", "--max", type=int, default=10000000, help="Set the maximum length of Latin phrase") + parser.add_argument("-m", "--min", default=0, type=int, help="Set the minimum length of the Latin phrase") + parser.add_argument("-M", "--max", default=10000000, type=int, help="Set the maximum length of Latin phrase") parser.add_argument("-n", "--notes", action='store_true', help="Print any notes on phrase") args = parser.parse_args() - id = [] + right_length = [] + # Find phrases of the right size with open('/usr/share/phrases/phrases.csv') as f: reader = csv.reader(f) - for row in reader: - if args.max >= int(row[len(row) - 1]) >= args.min: - id.append(row[0]) - chosen = id[random.randint(0, len(id))] + all_lines = list(reader) + next(reader, None) # skip header + for row in all_lines: + try: + if args.max >= int(row[4]) >= args.min: # generate a shortlist of phrases of the right length + right_length.append(row[0]) + except: + pass # skip malformed rows - with open('/usr/share/phrases/phrases.csv') as f: - reader = csv.reader(f) - for row in reader: - if row[0] == chosen: - if args.id: - print(row[0]) - if args.latin: - print(row[1]) - if args.english: - print(row[2]) - if args.notes: - print(row[3]) - if not len(sys.argv) > 1: - print(row[1]) + try: + chosen = int(right_length[random.randint(0, len(right_length) - 1)]) # choose a random id from the shortlist + except: + sys.exit("No phrase within the given parameters!") + + # Output as specified in flags + if not (args.english or args.latin or args.notes): + print(all_lines[chosen][1]) + else: + if args.id: + print(all_lines[chosen][1]) + if args.latin: + print(all_lines[chosen][1]) + if args.english: + print(all_lines[chosen][2]) + if args.notes: + print(all_lines[chosen][3]) if __name__ == "__main__": main()