Home > Backend Development > Python Tutorial > How to convert python numbers to Chinese

How to convert python numbers to Chinese

藏色散人
Release: 2023-01-05 16:13:53
Original
24096 people have browsed it

How to convert python numbers to Chinese: 1. Convert Arabic numerals into Chinese through the "def num_to_char(num)..." method; 2. Convert Arabic numerals into Chinese through the "def _to_chinese4(num)..." method Just convert the numbers into corresponding Chinese.

How to convert python numbers to Chinese

The operating environment of this article: windows7 system, DELL G3 computer, python3.5 version

Python realizes the conversion of Arabic numerals into Chinese

The first conversion method:

    1  -->  一
    12   -->  一二
def num_to_char(num):
    """数字转中文"""
    num=str(num)
    new_str=""
    num_dict={"0":u"零","1":u"一","2":u"二","3":u"三","4":u"四","5":u"五","6":u"六","7":u"七","8":u"八","9":u"九"}
    listnum=list(num)
    # print(listnum)
    shu=[]
    for i in listnum:
        # print(num_dict[i])
        shu.append(num_dict[i])
    new_str="".join(shu)
    # print(new_str)
    return new_str
Copy after login

The second conversion method:

     1   -->   一
    12  -->   十二
    23  -->  二十三
_MAPPING = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', u'十', u'十一', u'十二', u'十三', u'十四', u'十五', u'十六', u'十七',u'十八', u'十九')
_P0 = (u'', u'十', u'百', u'千',)
_S4 = 10 ** 4
def _to_chinese4(num):
    assert (0 <= num and num < _S4)
    if num < 20:
        return _MAPPING[num]
    else:
        lst = []
        while num >= 10:
            lst.append(num % 10)
            num = num / 10
        lst.append(num)
        c = len(lst)  # 位数
        result = u&#39;&#39;
        for idx, val in enumerate(lst):
            val = int(val)
            if val != 0:
                result += _P0[idx] + _MAPPING[val]
                if idx < c - 1 and lst[idx + 1] == 0:
                    result += u&#39;零&#39;
        return result[::-1]
Copy after login

Recommended: "python video tutorial"

The above is the detailed content of How to convert python numbers to Chinese. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template