]> git.armaanb.net Git - phrases.git/blobdiff - phrases.py
add argparsing, branding
[phrases.git] / phrases.py
index bcf3f7367128bfb9de2ba3f9f1e66af48f071eee..39d6f0c7e59be1d3101d120fb89b57b669e68c5d 100755 (executable)
@@ -2,22 +2,13 @@
 # Display Latin famous phrases in the terminal
 # Armaan Bhojwani 2020
 
+import argparse
 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):
+def read_phrases(phrase_file):
     f = open(phrase_file, 'r')
     contents = f.read()
 
@@ -26,33 +17,44 @@ def _read_phrases(phrase_file):
     phrases = []
     cur = []
 
-    def save_if_nonempty(buf):
-        phrase = '\n'.join(buf)
-        if phrase.strip():
-            phrases.append(phrase)
-
     for line in lines:
         if delim.match(line):
-            save_if_nonempty(cur)
+            phrase = '\n'.join(cur)
+            if phrase.strip():
+                phrases.append(phrase)
             cur = []
             continue
-
         cur.append(line)
 
-    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)
+# Main program
+def main(args=sys.argv[1:]):
+    parser = argparse.ArgumentParser(description="Latin famous phrases in the terminal.")
+    parser.add_argument("-e", "--english", action='store_true', help="Output English.")
+    parser.add_argument("-l", "--latin", action='store_true', help="Output Latin (default)")
+    parser.add_argument("-n", "--notes", action='store_true', help="Output notes on phrase")
+    parser.add_argument("-m", "--min", type=int, help="Set the minimum length of latin")
+    parser.add_argument("-M", "--max", type=int, help="Set the maximum length of latin")
+    args = parser.parse_args()
+
+    phrases = list(read_phrases("/usr/share/phrases/phrases"))
+    randomRecord = random.randint(0, len(phrases) - 1)
     randphrase = phrases[randomRecord]
-    return randphrase.partition('\n')[0]
 
-# Main program
-def main():
-    print(get_random_phrase("/usr/share/phrases/phrases"))
+    if args.min:
+        while True:
+            randomRecord = random.randint(0, len(phrases) - 1)
+            randphrase = phrases[randomRecord]
+            if args.min <= len(randphrase.split('\n')[0]) <= args.max:
+                break
+    if args.latin:
+        print(randphrase.split('\n')[0])
+    if args.english:
+        print(randphrase.split('\n')[1])
+    if args.notes:
+        print(randphrase.split('\n')[2])
+    if not len(sys.argv) > 1:
+        print(randphrase.split('\n')[0])
 
 main()