前言:
今天需要用到将阿拉伯数字转换成英文(读音一样的)功能,百度也没有找到合适的程序,只能自己写一个了.
因为看了不少代码的例子,有一篇里面有一个’递归’,让我刚开始走了偏路(可能是真的能递归, 也可能他写的是汉字的),英语不好的我又搜加问英语读法规则,最后写出了这个.
代码里面肯定有可以简化的,也可能有错误的.但是基本要求满足了,可以用.现在就先发出来,以后发现错误再改
# -*- coding:utf8 -*-
# @Time : 2021/10/12 18:07
# @Author : cdl
# @File : 阿拉伯数字转换成英文.py
# version : Python3.8.5
'''
百位数的英文书写规则:
百位数个数基数词形式加“hundred”,表示几百,在几十几与百位间加上and。
千位以上数的英文书写规则:
千位数以上 从数字的右端向左端数起,每三位数加一个逗号“,”。
从右开始,第一个“,”前的数字后添加 thousand,第二个“,”前面的数字后添加 million,
第三个“,”前的数字后添加 billion。然后一节一节分别表示,两个逗号之间最大的数为百位数形式。
'''
ones = {1: "one", 2: "two", 3: "three", 4: "four",
5: "five", 6: "six", 7: "seven", 8: "eight",
9: "nine", 0: "zero", 10: "ten", 11: "eleven",
12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen",
16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'}
tens = {2: "twenty", 3: "thirty", 4: "forty",
5: "fifty", 6: "sixty", 7: "seventy",
8: "eighty", 9: "ninety", 1: "ten",}
def zero(num_str): # 数字是'0'
s_list = []
for num in num_str:
s_list.append(ones[int(num)])
return s_list
def num_word(num_str):
# print(num_str)
if num_str[0] == '0':
return ' '.join(zero(num_str))
num = eval(num_str.replace(',', ''))
word_list = []
if 0 == num:
word_list = [ones[num]]
while num:
if num < 1000:
word_list += it_thousand(num)
break
elif num < 1000000:
word_list += it_thousand(num//1000)+['million']
num %= 1000
continue
elif num < 1000000000:
word_list += it_thousand(num//1000000)+['billion']
num %= 1000000
if num < 1000:
word_list.append('and')
continue
elif num < 1000000000000:
word_list += it_thousand(num // 1000000000) + ['trillion']
num %= 1000000000
if num < 1000000:
word_list.append('and')
continue
return ' '.join(word_list)
def it_thousand(num): # 百位数的英文书写
word_list = []
if 0 == num:
word_list = ['and']
else:
while num:
if num <= 19:
word_list.append(ones[num])
break
elif num < 100:
word_list.append(tens[num // 10])
num %= 10
continue
else:
word_list.append(ones[num // 100])
word_list.append('hundred')
num %= 100
if num:
word_list.append('and')
return word_list
if __name__ == '__main__':
str_s = '1,234,567,890,123,456,789'
str_3 = '190,123,000,425'
print(num_word(str_3))
print(it_thousand(123))



