DEV Community

Cover image for A Python function to convert Chinese number to Arabic number
01kg
01kg

Posted on

A Python function to convert Chinese number to Arabic number

TL;DR

def chinese_to_arabic(chinese_number):
    chinese_arabic_dict = {
        '': 0, '': 1, '': 2, '': 3, '': 4,
        '': 5, '': 6, '': 7, '': 8, '': 9,
        '': 10, '': 100, '': 1000, '': 10000, '亿': 100000000
    }

    total = 0
    r = 1  # The factor that will multiply the unit, such as 10 for 十, 100 for 百.

    for i in range(len(chinese_number) - 1, -1, -1):
        val = chinese_arabic_dict.get(chinese_number[i])
        if val >= 10 and i == 0:  # This is for when the Chinese number begins with 十 (such as 十一).
            if val > r:
                r = val
                total = total + val
            else:
                r = r * val
        elif val >= 10:
            if val > r:
                r = val
            else:
                r = r * val
        else:
            total = total + r * val

    return total


print(chinese_to_arabic(''))  # Should return 1
print(chinese_to_arabic(''))  # Should return 2
print(chinese_to_arabic('十一'))  # Should return 11
print(chinese_to_arabic('二十五'))  # Should return 25
print(chinese_to_arabic('一百三十四'))  # Should return 134
print(chinese_to_arabic('七千八百九十七'))  # Should return 7897
Enter fullscreen mode Exit fullscreen mode

Thanks to the help of ChatGPT 4!

Origin prompt:

Would you write a python function to convert chinese number to arabic number?

一 = 1
二 = 2
十一 = 11
二十五 = 25
一百三十四 = 134
七千八百九十七 = 7897
...

Enter fullscreen mode Exit fullscreen mode

Top comments (0)