gpt4 book ai didi

python - 有没有办法将数字单词转换为整数?

转载 作者:IT老高 更新时间:2023-10-28 20:23:31 24 4
gpt4 key购买 nike

我需要将one转换成1two转换成2等等。

有没有办法通过库或类或任何东西来做到这一点?

最佳答案

这段代码的大部分是设置numwords dict,它只在第一次调用时完成。

def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]

tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

scales = ["hundred", "thousand", "million", "billion", "trillion"]

numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)

current = result = 0
for word in textnum.split():
if word not in numwords:
raise Exception("Illegal word: " + word)

scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0

return result + current

print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven")
#7100031337

关于python - 有没有办法将数字单词转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/493174/

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