小能豆

有没有办法将数字转换为整数?

python

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

有没有办法通过图书馆、课程或其他东西来做到这一点?


阅读 206

收藏
2023-11-15

共2个答案

小能豆

此代码的大部分内容是设置 numwords 字典,这仅在第一次调用时完成。

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
2023-11-15
小能豆

你可以创建一个函数,将英文单词表示的数字转换为相应的整数。这可以通过使用字典来实现,其中键是单词,值是相应的整数。以下是一个简单的示例:

def word_to_number(word):
    number_dict = {
        'one': 1,
        'two': 2,
        'three': 3,
        'four': 4,
        # 继续添加其他数字和对应的单词
    }

    # 将单词转换为小写,以确保不区分大小写
    lower_word = word.lower()

    # 使用字典的get方法,如果单词不存在于字典中,则返回None
    return number_dict.get(lower_word)

# 测试示例
word = 'two'
result = word_to_number(word)

if result is not None:
    print(f'The number corresponding to "{word}" is: {result}')
else:
    print(f'Sorry, "{word}" is not a valid word for conversion.')

在这个例子中,word_to_number 函数接受一个单词作为参数,将其转换为小写,然后查找字典中相应的整数。如果单词不在字典中,返回 None。你可以根据需要扩展字典,添加其他单词和相应的整数。

2023-11-15