A2oz

How to Convert Words to Numbers in Python?

Published in Programming 2 mins read

You can easily convert words representing numbers to their numerical counterparts in Python using the int() function in combination with a dictionary mapping words to their corresponding numbers. Here's a simple example:

number_words = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5,
    "six": 6,
    "seven": 7,
    "eight": 8,
    "nine": 9,
    "ten": 10,
}

word = "five"
number = number_words.get(word.lower())

if number:
    print(f"The number for '{word}' is: {number}")
else:
    print(f"'{word}' is not a recognized number word.")

This code snippet defines a dictionary number_words that maps the words "one" to "ten" to their corresponding numerical values. It then takes a word input, converts it to lowercase for case-insensitive matching, and retrieves the associated number from the dictionary. If the word is found, it prints the corresponding number; otherwise, it indicates that the word is not recognized.

Here are some additional points to consider:

  • Handling larger numbers: You can expand the dictionary to include words representing larger numbers (e.g., "eleven", "twelve", "twenty", "hundred", "thousand").
  • Handling negative numbers: You can add a conditional check to identify negative signs ("minus", "negative") and adjust the resulting number accordingly.
  • Handling decimal numbers: You can incorporate words like "point", "decimal", and "and" to convert decimal numbers.
  • Using external libraries: For more complex scenarios, you might consider using libraries like num2words which provide more robust and flexible functionality for converting words to numbers.

By understanding the basic principles and leveraging available resources, you can effectively convert words to numbers in Python for various applications.

Related Articles