中文字符转换__int__
本帖最后由 BrightXiong 于 2023-2-16 22:11 编辑# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2023/2/16 21:48
# @Author : xiongming
# @File : zh_int.py
# @Desc : 输入中文,转成数字
class ZH_INT:
def __init__(self, num):
self.num = num
def __int__(self):
try:
return int(self.num)
except ValueError:
zh = {"零":0, "一":1, "三":3, "四":4, "五": 5,
"六":6, "七":7, "八":8, "九":9, "十":10,
"壹":1, "贰":2, "叁":3, "肆":4, "伍":5,
"陆":6, "柒":7, "捌":8, "玖":9}
result = 0
for each in self.num:
if each in zh:
result += zh
else:
result += int(each)
result *= 10
#双斜杠(//)表示地板除,即先做除法(/),然后向下取整(floor)
return result // 10
n1 = ZH_INT("520")
s1 = int(n1) # 520
print(s1)
n2 = ZH_INT("伍贰零")
s2 = int(n2) # 520
print(s2)
n3 = ZH_INT(3.14)
s3 = int(n3)
print(s3)
n4 = ZH_INT("伍贰零1314")
s4 = int(n4)
print(s4)
页:
[1]