View Single Post
Old 09-22-2021, 05:15 PM   #12
Ted Friesen
Nameless Being
 
Quote:
Originally Posted by jbacelar View Post
What I use.

Arabic to Roman
Search (eg):
(>Chapter )(\d+)(<)

Regex-function:
Code:
def num_roman(input):
    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')
    result = ""
    input=int(input)
    for i in range(len(ints)):
        count = input//ints[i]
        result += nums[i] * count
        input -= ints[i] * count
    return result
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    return match.group(1)+str(num_roman(match.group(2)))+match.group(3)
Roman to Arabic
Search (eg):
(>Chapter )(.+?)(<)

Regex-function:

Code:
numeral_map = zip(
    (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1),
    ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
)
	   
def arabic_num(n):
    n = unicode(n).upper()
    i = result = 0
    for integer, numeral in numeral_map:
        while n[i:i + len(numeral)] == numeral:
            result += integer
            i += len(numeral)
    return result
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    return match.group(1)+str(arabic_num(match.group(2)))+match.group(3)
I know it's been a while, but I just found this and want to thank you for posting. All I had to do to get it to work was to change unicode to str.
  Reply With Quote