]> git.armaanb.net Git - phrases.git/blob - phrases.py
Finish basic form of program
[phrases.git] / phrases.py
1 #!/usr/bin/env python3
2 # Display famous phrases in the terminal
3 # Armaan Bhojwani 2020
4
5 import random
6 import os
7 import sys
8 import re
9
10 def _random_int(start, end):
11 # Use system random if available, otherwise, use Python's
12     try:
13         r = random.SystemRandom()
14     except:
15         r = random
16
17     return r.randint(start, end)
18
19 def _read_fortunes(fortune_file):
20     f = open(fortune_file, 'r')
21     contents = f.read()
22
23     lines = [line.rstrip() for line in contents.split('\n')]
24     delim = re.compile(r'^%$')
25     fortunes = []
26     cur = []
27
28     def save_if_nonempty(buf):
29         fortune = '\n'.join(buf)
30         if fortune.strip():
31             fortunes.append(fortune)
32
33     for line in lines:
34         if delim.match(line):
35             save_if_nonempty(cur)
36             cur = []
37             continue
38
39         cur.append(line)
40
41     if cur:
42         save_if_nonempty(cur)
43
44     return fortunes
45
46 def get_random_fortune(fortune_file):
47     fortunes = list(_read_fortunes(fortune_file))
48     randomRecord = _random_int(0, len(fortunes) - 1)
49     randFortune = fortunes[randomRecord]
50     return randFortune.partition('\n')[0]
51
52 def main():
53     print(get_random_fortune("/usr/share/phrases/phrases"))
54
55 main()