首页  >  文章  >  后端开发  >  如何在 Python 中将数字单词转换为整数?

如何在 Python 中将数字单词转换为整数?

Patricia Arquette
Patricia Arquette原创
2024-11-20 18:44:20772浏览

How Can I Convert Number Words to Integers in Python?

将数字单词转换为整数

通常,需要转换表示为文本的数字单词(例如,“一”、“二” ") 转化为相应的整数

解决方案:

为了促进这种转换,引入了一个名为 text2int 的 Python 函数,它利用数字词 (numwords) 的综合字典来映射文本表示为整数。这是实现:

def text2int(textnum, numwords={}):
    if not numwords:
        # Initialize the numwords dictionary only on the first call
        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

示例:

考虑以下输入:“70亿1亿31337”

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

以上是如何在 Python 中将数字单词转换为整数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn