栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 翻译英语数字成阿拉伯数字

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 翻译英语数字成阿拉伯数字

DESCRIPTION:

In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.

Examples:

  • "one" => 1
  • "twenty" => 20
  • "two hundred forty-six" => 246
  • "seven hundred eighty-three thousand nine hundred and nineteen" => 783919

Additional Notes:

  • The minimum number is "zero" (inclusively)
  • The maximum number, which must be supported is 1 million (inclusively)
  • The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not
  • All tested numbers are valid, you don't need to validate them
dict1 = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5,
         'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11,
         'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16,
         'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30,
         'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90}
dict2 = {'hundred': '*100 ', 'thousand': '*1000 ', 'million': '*1000000 ', 'and': '+0 '}

en_string = 'one thousand'

temp = list(en_string.split(' '))
en_list = []
for i in range(len(temp)):
    if '-' in temp[i]:
        en_list += temp[i].split('-')
    else:
        en_list.append(temp[i])
# print(en_list)
str_num = '0'
for en in en_list:
    if en in dict1:
        str_num += '+' + str(dict1[en])
    elif en in dict2:
        str_num = str_num + dict2[en]
# print(str_num)
if '*1000 ' in str_num:
    list_num = str_num.split('*1000 ')
    if list_num[-1] == '':
        res = 0
    else:
        res = eval(list_num[-1])
    for n in list_num[0:-1]:
        res = res + eval(n) * 1000
    print(res)
else:
    print(eval(str_num))

可能不全面,但是大部分是可以了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/961184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号