#!/usr/bin/env python3
-# Display famous phrases in the terminal
+# Display Latin famous phrases in the terminal
# Armaan Bhojwani 2020
import random
import sys
import re
-def _random_int(start, end):
# Use system random if available, otherwise, use Python's
+def _random_int(start, end):
try:
r = random.SystemRandom()
except:
return r.randint(start, end)
-def _read_fortunes(fortune_file):
- f = open(fortune_file, 'r')
+# 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'^%$')
- fortunes = []
+ phrases = []
cur = []
def save_if_nonempty(buf):
- fortune = '\n'.join(buf)
- if fortune.strip():
- fortunes.append(fortune)
+ phrase = '\n'.join(buf)
+ if phrase.strip():
+ phrases.append(phrase)
for line in lines:
if delim.match(line):
if cur:
save_if_nonempty(cur)
- return fortunes
+ return phrases
-def get_random_fortune(fortune_file):
- fortunes = list(_read_fortunes(fortune_file))
- randomRecord = _random_int(0, len(fortunes) - 1)
- randFortune = fortunes[randomRecord]
- return randFortune.partition('\n')[0]
+# 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]
+# Main program
def main():
- print(get_random_fortune("/usr/share/phrases/phrases"))
+ print(get_random_phrase("/usr/share/phrases/phrases"))
main()