Home > Article > Backend Development > How Can I Convert Number Words to Integers in Python?
Converting Number Words to Integers
Often, there's a need to convert numerical words expressed as text (e.g., "one", "two") into their corresponding integer values.
Solution:
To facilitate this conversion, a Python function called text2int is introduced, which utilizes a comprehensive dictionary of number words (numwords) to map textual representations to integers. Here's the implementation:
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
Example:
Consider the following input: "seven billion one hundred million thirty one thousand three hundred thirty seven"
print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven") # 7100031337
The above is the detailed content of How Can I Convert Number Words to Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!