X-Git-Url: https://git.mdrn.pl/librarian.git/blobdiff_plain/fefdce4e24f9e397df5538fe6e7f54b5ece4d841..1e1abb45277301597bcbb54d17675330bedd7fc5:/src/librarian/util.py?ds=inline diff --git a/src/librarian/util.py b/src/librarian/util.py index c302084..2c6b773 100644 --- a/src/librarian/util.py +++ b/src/librarian/util.py @@ -1,10 +1,11 @@ -# Functions to convert between integers and Roman numerals. Doctest examples included. -# by Paul Winkler +# Functions to convert between integers and Roman numerals. +# by Paul Winkler # http://code.activestate.com/recipes/81611-roman-numerals/ # PSFL (GPL compatible) from __future__ import print_function, unicode_literals import os +import six def int_to_roman(input): @@ -51,12 +52,13 @@ def int_to_roman(input): >>> print(int_to_roman(1999)) MCMXCIX """ - if type(input) != type(1): + if not isinstance(input, int): raise TypeError("expected integer, got %s" % type(input)) if not 0 < input < 4000: raise ValueError("Argument must be between 1 and 3999") ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) - nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') + nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', + 'I') result = "" for i in range(len(ints)): count = int(input / ints[i]) @@ -64,10 +66,11 @@ def int_to_roman(input): input -= ints[i] * count return result + def roman_to_int(input): """ Convert a roman numeral to an integer. - + >>> r = list(range(1, 4000)) >>> nums = [int_to_roman(i) for i in r] >>> ints = [roman_to_int(n) for n in nums] @@ -91,21 +94,21 @@ def roman_to_int(input): ... ValueError: input is not a valid roman numeral: IL """ - if type(input) != type(""): + if not isinstance(input, six.text_type): raise TypeError("expected string, got %s" % type(input)) input = input.upper() nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I'] ints = [1000, 500, 100, 50, 10, 5, 1] places = [] for c in input: - if not c in nums: + if c not in nums: raise ValueError("input is not a valid roman numeral: %s" % input) for i in range(len(input)): c = input[i] value = ints[nums.index(c)] # If the next place holds a larger number, this value is negative. try: - nextvalue = ints[nums.index(input[i +1])] + nextvalue = ints[nums.index(input[i + 1])] if nextvalue > value: value *= -1 except IndexError: @@ -113,7 +116,8 @@ def roman_to_int(input): pass places.append(value) sum = 0 - for n in places: sum += n + for n in places: + sum += n # Easiest test for validity... if int_to_roman(sum) == input: return sum @@ -124,3 +128,14 @@ def roman_to_int(input): def makedirs(path): if not os.path.isdir(path): os.makedirs(path) + + +def get_translation(language): + import gettext + from .functions import lang_code_3to2 + + return gettext.translation( + 'messages', + localedir=os.path.join(os.path.dirname(__file__), 'locale'), + languages=[lang_code_3to2(language)], + )