gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:09:54 25 4
gpt4 key购买 nike

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

这是练习:在这个套路中,我们要将字符串转换为整数。字符串仅表示单词中的数字。例子:“一”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. 有时人们会在数字之间加上。喜欢:37021
  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

关于python - 如何在python中将字符串转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69722073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com