繁体   English   中英

如何在python中将字符串转换为数字

[英]How to convert string into numbers in python

我在 codewars 中看到一个有趣的 python 练习。它是关于将字符串转换为数字。我想要一些建议或指导来解决这个 python 练习。谢谢

这是练习:在这个 kata 中,我们想将字符串转换为整数。 字符串只是用单词表示数字。 示例:“一个”1

这是我的代码:

def parse_int(string):
    dict_of_numbers={ "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,"thousand":1000,"hundred":100}

    string=string.replace(' ','-')
    numbers=string.split('-')
    created_number=0
    for number in numbers:
        for key,value in dict_of_numbers.items():
            if number==key:
                created_number+=value
    return created_number

我有一个解决方案,我没有针对大量数字对其进行测试,但它可能会给您一些想法:

  1. 口语有时相加有时相乘。
  2. 有时人们会在数字之间加上and 喜欢: thirty seven thousand and twenty one
  3. 不要使用[]从您的字典中获取价值。 使用get方法。 因此,如果没有与数字对应的数据,则您可以控制退货。
  4. 使用str的.lower()降低字符串中的字母,避免大写、小写问题

我写的代码看起来像:

def parse_int(string):
    dict_of_numbers = {"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,
                       "thousand": 1000, "hundred": 100}

    string = string.replace(" and ", " ")
    the_number = 0
    for each in string.lower().split():
        if each in ["hundred", "thousand"]:
            the_number *= dict_of_numbers.get(each, 1)
        else:
            the_number += dict_of_numbers.get(each, 0)


    return the_number


print(parse_int("thirty seven thousand and twenty two")) # 37022

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM