|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Author : Martin Schuh <[email protected]> |
| 4 | +Date : 2022-11-21 |
| 5 | +Purpose: Gematria |
| 6 | +""" |
| 7 | + |
| 8 | +import argparse |
| 9 | +import os |
| 10 | +import io |
| 11 | +import string |
| 12 | +from typing import Final |
| 13 | +from functools import reduce |
| 14 | + |
| 15 | + |
| 16 | +VALID_CHARS: Final = string.ascii_letters + string.digits |
| 17 | + |
| 18 | + |
| 19 | +# -------------------------------------------------- |
| 20 | +def get_args(): |
| 21 | + """Get command-line arguments""" |
| 22 | + |
| 23 | + parser = argparse.ArgumentParser( |
| 24 | + description='Gematria', |
| 25 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| 26 | + |
| 27 | + parser.add_argument('text', |
| 28 | + metavar='text', |
| 29 | + type=str, |
| 30 | + help='Input text or file') |
| 31 | + |
| 32 | + args = parser.parse_args() |
| 33 | + |
| 34 | + if os.path.isfile(args.text): |
| 35 | + args.text = open(args.text, encoding='utf-8') |
| 36 | + else: |
| 37 | + args.text = io.StringIO(args.text + '\n') |
| 38 | + |
| 39 | + return args |
| 40 | + |
| 41 | + |
| 42 | +# -------------------------------------------------- |
| 43 | +def main(): |
| 44 | + """Make a jazz noise here""" |
| 45 | + |
| 46 | + args = get_args() |
| 47 | + |
| 48 | + for text in args.text: |
| 49 | + print(' '.join([word2num(word) for word in text.split()])) |
| 50 | + |
| 51 | + |
| 52 | +# -------------------------------------------------- |
| 53 | +def word2num(word): |
| 54 | + """Sums up ordinals of a word""" |
| 55 | + return str(reduce(lambda x, y: x + y, map(value, list(word)))) |
| 56 | + |
| 57 | + |
| 58 | +def value(char): |
| 59 | + """Maps valid char to ordinal value""" |
| 60 | + return ord(char) if char in VALID_CHARS else 0 |
| 61 | + |
| 62 | + |
| 63 | +def test_value(): |
| 64 | + """Test value""" |
| 65 | + assert value("a") == 97 |
| 66 | + assert value("Z") == 90 |
| 67 | + assert value("'") == 0 |
| 68 | + |
| 69 | + |
| 70 | +def test_word2num(): |
| 71 | + """Test word2num""" |
| 72 | + assert word2num("a") == "97" |
| 73 | + assert word2num("abc") == "294" |
| 74 | + assert word2num("ab'c") == "294" |
| 75 | + assert word2num("4a-b'c,") == "346" |
| 76 | + |
| 77 | + |
| 78 | +# -------------------------------------------------- |
| 79 | +if __name__ == '__main__': |
| 80 | + main() |
0 commit comments