How to convert numbers to Chinese characters with python?

In most cases, Chinese characters are more formal than numbers.

For example, "2019" is more like an official document, while "2019" is more like a personal diary.

In addition, Chinese characters can also be used to make tongue twisters! It is much harder to use numbers. Or give a chestnut:

14 is 14, 40 is 40.

It looks very young.

Fourteen is fourteen and forty is forty.

There is a feeling of scented lips and teeth.

There are 44 stone lions in front of the mountain and 44 purple persimmon trees behind the mountain.

It feels like a boring running account.

There are 44 stone lions in front of the mountain and 44 purple persimmon trees behind the mountain.

It feels like a catchy song.

So, how to realize the function of converting numbers to Chinese characters with python? The code is not long and not difficult:

han_list = ["零" , "一" , "二" , "三" , "四" , "五" , "六" , "七" , "八" , "九"]
unit_list = ["","","十" , "百" , "千"]

def four_to_han(num_str):
    result = ""
    num_len = len(num_str)
    for i in range(num_len):
        num = int(num_str[i])
        if i!=num_len-1:
            if num!=0:
                result=result+han_list[num]+unit_list[num_len-i]
            else:
                if result[-1]=='零':
                    continue
                else:
                    result=result+'零'
        else:
            if num!=0:
                result += han_list[num]

    return result

The above code can only convert up to four digits.

What if the number of digits exceeds four?

The idea is still similar, except that the unit of 5-8 digits is "10,000", the unit of 9-12 digits is "100 million", and the unit of 13-16 digits is "mega".

Guess you like

Origin blog.csdn.net/esa72ya/article/details/106050780