]> git.armaanb.net Git - phrases.git/blobdiff - phrases.py
add argument parsing, fix program logic
[phrases.git] / phrases.py
index bcf3f7367128bfb9de2ba3f9f1e66af48f071eee..63199d141d996cccc70d160ad3f71438f2909a32 100755 (executable)
@@ -2,57 +2,85 @@
 # Display Latin famous phrases in the terminal
 # Armaan Bhojwani 2020
 
+import argparse
+import csv
 import random
-import os
 import sys
-import re
 
-# Use system random if available, otherwise, use Python's
-def _random_int(start, end):
-    try:
-        r = random.SystemRandom()
-    except:
-        r = random
-
-    return r.randint(start, end)
-
-# Create list of phrases from phrase file
-def _read_phrases(phrase_file):
-    f = open(phrase_file, 'r')
-    contents = f.read()
-
-    lines = [line.rstrip() for line in contents.split('\n')]
-    delim = re.compile(r'^%$')
-    phrases = []
-    cur = []
+def main(args=sys.argv[1:]):
+    # Argument parsing
+    parser = argparse.ArgumentParser(
+        description="Latin famous phrases in the terminal.")
+    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("-e", "--english",
+                        action='store_true',
+                        help="print the English translation.")
+    parser.add_argument("-n", "--notes",
+                        action='store_true',
+                        help="print any notes on 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("-p", "--num",
+                        action='store_true',
+                        help="print number of possibilities within constraints")
+    parser.add_argument("-f", "--file",
+                        default="/usr/share/phrases/phrases.csv",
+                        help="set the location of the phrase file")
+    args = parser.parse_args()
 
-    def save_if_nonempty(buf):
-        phrase = '\n'.join(buf)
-        if phrase.strip():
-            phrases.append(phrase)
+    right_length = []
 
-    for line in lines:
-        if delim.match(line):
-            save_if_nonempty(cur)
-            cur = []
-            continue
+    # convert csv file into list
+    with open(args.file) as f:
+        reader = csv.reader(f)
+        next(reader, None) # skip header
+        all_lines = list(reader) 
+    f.close()
 
-        cur.append(line)
+    # iterate through all the phrases
+    for row in all_lines:
+        try: # generate a shortlist of phrases of the right length
+            if args.max >= int(row[4]) >= args.min:
+                right_length.append(row[0])
+        except: # skip malformed rows without exiting
+            pass
 
-    if cur:
-        save_if_nonempty(cur)
-
-    return phrases
-
-# Return a random phrase from the phrases list
-def get_random_phrase(phrase_file):
-    phrases = list(_read_phrases(phrase_file))
-    randomRecord = _random_int(0, len(phrases) - 1)
-    randphrase = phrases[randomRecord]
-    return randphrase.partition('\n')[0]
+    try: # choose a random id from the shortlist
+        chosen = int(right_length[random.randint(0, len(right_length) - 1)])
+    except:
+        sys.exit("No phrase within the given parameters!")
 
-# Main program
-def main():
-    print(get_random_phrase("/usr/share/phrases/phrases"))
+    # Output as specified in flags
+    for row in all_lines:
+        if int(row[0]) == chosen:
+            if not (args.id
+                    or args.latin
+                    or args.english
+                    or args.notes
+                    or args.num):
+                print(row[1])
+            else:
+                if args.id:
+                    print(row[1])
+                if args.latin:
+                    print(row[1])
+                if args.english:
+                    print(row[2])
+                if args.notes:
+                    print(row[3])
+                if args.num:
+                    print(len(right_length))
 
-main()
+if __name__ == "__main__":
+    main()