homes/common/.local/bin/json-fortune

61 lines
1.4 KiB
Python
Executable file

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Get a fortune from a JSON file.
File is under EUPL1.2
Author: kujiu
"""
import json
import argparse
import logging
import sys
import os.path
import random
logger = logging.getLogger(__name__)
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.WARNING)
logger.addHandler(ch)
def get_quote(srcfile):
"""
Get a quote
"""
with open(srcfile) as fin:
quotes = json.load(fin)
quote = ""
count = 0
while not quote and count < 50:
count += 1
lang = random.choice([lang for lang in quotes.keys()])
category = random.choice([cat for cat in quotes[lang].keys()])
if not quotes[lang][category]:
continue
author = random.choice(
[author for author in quotes[lang][category].keys()])
if not quotes[lang][category][author]:
continue
quote = random.choice(quotes[lang][category][author])
if quote:
quote += "\n-- %s" % author
return quote
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Get a quote from JSON file.")
parser.add_argument(
'--source', default='~/.fortunes.json',
help='JSON file with quotes')
options = parser.parse_args()
source = os.path.expanduser(
os.path.expandvars(options.source)
)
print(get_quote(source))