有没有办法在不丢失前导零的情况下将数字、字符串中的 ether 或 int 转换为单词?我正在尝试将日期和时间以及电话号码转换为单词,但是第二次我将字符串值转换为 int 我丢失了前导零。
这是我现在对单词进行数字计算的代码,只要没有前导零,它就可以很好地工作。这是我的问题的一个例子......假设我正在转动一个日期 08-02-2004 我不希望这个输出为零八零二......等等,但我要在当前状态下这样做我会必须做一些关于方法的事情......除非我错过了一些东西。
units = ["", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine "]
teens = ["", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
thousands = ["","thousand", "million", "billion", "trillion",
"quadrillion", "quintillion", "sextillion", "septillion", "octillion",
"nonillion", "decillion", "undecillion", "duodecillion", "tredecillion",
"quattuordecillion", "sexdecillion", "septendecillion", "octodecillion",
"novemdecillion", "vigintillion "]
def numToWords(self, num):
words = []
if num == 0:
words.append("zero")
else:
numStr = "%d" % num
numStrLen = len(numStr)
groups = (numStrLen + 2) / 3
numStr = numStr.zfill(groups * 3)
for i in range(0, groups*3, 3):
h = int(numStr[i])
t = int(numStr[i+1])
u = int(numStr[i+2])
g = groups - (i / 3 + 1)
if h >= 1:
words.append(units[h])
words.append("hundred")
if t > 1:
words.append(tens[t])
if u >= 1:
words.append(units[u])
elif t == 1:
if u >= 1:
words.append(teens[u])
else:
words.append(tens[t])
else:
if u >= 1:
words.append(units[u])
if g >= 1 and (h + t + u) > 0:
words.append(thousands[g])
return ' '.join([w for w in words])
对此的任何帮助或建议将不胜感激。