Open In App

Convert numeric words to numbers

Last Updated : 19 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S, containing numeric words, the task is to convert the given string to the actual number.

Example: 

Input: S = “zero four zero one”
Output: 0401

Input: S = “four zero one four”
Output: 4014

Method #1: Using loop + join() + split() 

One of the ways to solve this problem is to use a map, where one can map the numeric with words and then split the strings and rejoin using mapping to numbers. 

Python3




# Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using join() + split()
 
help_dict = {
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'zero': '0'
}
 
# initializing string
test_str = "zero four zero one"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert numeric words to numbers
# Using join() + split()
res = ''.join(help_dict[ele] for ele in test_str.split())
 
# printing result
print("The string after performing replace : " + res)


Output

The original string is : zero four zero one
The string after performing replace : 0401

Time complexity: O(n)
Auxiliary space: O(n), where n is length of string.

Method #2: Using word2number library 

This problem can also be solved using PyPI library word2number. It has inbuilt functions that convert words to numbers. 

Python3




# Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using word2number
from word2number import w2n
 
# initializing string
test_str = "zero four zero one"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert numeric words to numbers
# Using word2number
res = w2n.word_to_num(test_str)
 
# printing result
print("The string after performing replace : " + str(res))


Time complexity: O(n)
Auxiliary space: O(n)

Approach 2: Using Regular Expressions (re)

We can use the re module in Python to find all the word occurrences in the string and then use a dictionary to map the words to numbers. After that, we can use the re.sub function to replace all the word occurrences with their corresponding numbers.

Python3




import re
 
def convert_to_numbers(s):
   
    words_to_numbers = {
        'one': '1',
        'two': '2',
        'three': '3',
        'four': '4',
        'five': '5',
        'six': '6',
        'seven': '7',
        'eight': '8',
        'nine': '9',
        'zero': '0'
    }
 
    pattern = re.compile(r'\b(' + '|'.join(words_to_numbers.keys()) + r')\b')
    return re.sub(pattern, lambda x: words_to_numbers[x.group()], s)
 
 
# Example usage:
s = "zero four zero one"
print(convert_to_numbers(s))


Output

0 4 0 1

Time complexity: O(n)
Auxiliary space: O(n)

Method 4: Using dictionary

Steps: 

  1. Split the input string into words using the split() method, and store the resulting list of words in variable words.
  2. We use a list comprehension to map each word in the list words to its corresponding digit using the word_to_digit dictionary and store the resulting list of digits in variable digits.
  3. Join the list of digits into a string using the join() method, and store the resulting string in a variable result.
  4. Print the original string and the result.

Python3




# Define a dictionary that maps
# numeric words to their corresponding digits
word_to_digit = {
    'zero': '0',
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9'
}
 
# Initializing string
test_str = 'zero four zero one'
 
# Split the input string into words
words = test_str.split()
 
# Map each word to its corresponding digit using the dictionary
digits = [word_to_digit[word] for word in words]
 
# Join the resulting list of digits into a string
result = ''.join(digits)
 
# Print the original string and the result
print('The original string is:', test_str)
print('The string after performing replace:', result)


Output

The original string is: zero four zero one
The string after performing replace: 0401

Time complexity: O(n), where n is the length of the input string test_str, because we need to traverse the string once to split it into words and once more to map each word to its corresponding digit.
Auxiliary space: O(1), because we only need to store the dictionary, the list of words, the list of digits, and the resulting string, which do not depend on the size of the input.

Method 5: Using list comprehension

This approach uses a list comprehension to iterate through the words in the input string and convert each word to its corresponding digit using a series of if/else statements. The resulting digits are concatenated to form the output string.

Steps:

  1. Split the input string into individual words using list comprehension, iterate through the words in the string, and convert each word to its corresponding digit using if/else statements.
  2. Concatenate the resulting digits to form the output string.
  3. Print the output string.

Python3




original_string = 'zero four zero one'
 
result = ''.join(['0' if word == 'zero' else '1' if word == 'one' else '2' if word == 'two' else '3' if word == 'three' else '4' if word == 'four' else '5' if word == 'five' else '6' if word == 'six' else '7' if word == 'seven' else '8' if word == 'eight' else '9' for word in original_string.split()])
 
print(result)


Output

0401

Time complexity: O(n), where n is the number of words in the input string.
Auxiliary Space: O(n), where n is the number of words in the input string.

Method 6: Using a list of tuples

Python3




# Define a list of tuples that maps numeric words
# to their corresponding digits
word_digit_pairs = [
    ('zero', '0'),
    ('one', '1'),
    ('two', '2'),
    ('three', '3'),
    ('four', '4'),
    ('five', '5'),
    ('six', '6'),
    ('seven', '7'),
    ('eight', '8'),
    ('nine', '9')
]
 
# Define the input string
test_str = 'zero four zero one'
 
# Iterate over each word-digit pair and replacing
# the words with digits in the input string
for word, digit in word_digit_pairs:
    test_str = test_str.replace(word, digit)
 
# Print the original string and the result
print('The original string is:', test_str)


Output

The original string is: 0 4 0 1

Time complexity: O(K) where K is the length of the input string and the number of word-digit pairs in the list. 
Auxiliary space: O(1) since we are not using any additional data structures that scale with the input size.



Similar Reads

Remove uppercase, lowercase, special, numeric, and non-numeric characters from a String
Given string str of length N, the task is to remove uppercase, lowercase, special, numeric, and non-numeric characters from this string and print the string after the simultaneous modifications. Examples: Input: str = “GFGgfg123$%” Output: After removing uppercase characters: gfg123$% After removing lowercase characters: GFG123$% After removing spe
10 min read
Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
15+ min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Convert a Mobile Numeric Keypad sequence to equivalent sentence
Given a string S of size N, consisting of digits [0 - 9] and character '.', the task is to print the string that can be obtained by pressing the mobile keypad in the given sequence. Note: '.' represents a break while typing. Below is the image to represent the characters associated with each number in the keypad. Examples: Input: S = "234"Output: A
9 min read
Convert a sentence into its equivalent mobile numeric keypad sequence
Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence.  Examples :  Input: GEEKSFORGEEKSOutput: 4333355777733366677743333557777Explanation: For obtaining a number, we need to press a number corresponding to that character for a number of times equal to the position of the character. For example, for
6 min read
Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K
Given a numeric string S consisting of N digits and a positive integer K, the task is to check if the given string can be split into more than one substrings with difference between consecutive substrings equal to K. Examples: Input: S = "8642", K = 2Output: YesExplanation: Split the given string as {"8", "6", "4", "2"}. Now, the difference between
6 min read
Convert given Array of Integers into Words
Given an array arr[] of N elements which are in range [0, 9]. the task is to convert each array element into its numeric strings. Examples: Input: arr[] = [1, 4, 3, 2, 6]Output: one four three two six Input: arr[]= [0, 4, 4, 6, 9]Output: zero four four six nine Approach: The problem can be solved with the help of map. Follow the steps given below:
4 min read
Program to convert a given number to words
Given an integer N, the task is to convert the given number into words. Examples : Input: N = 438237764Output: Four Hundred Thirty Eight Million Two Hundred Thirty Seven Thousand Seven Hundred Sixty Four Input: N = 1000Output: One Thousand Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Approach: This approach is
14 min read
Convert given time into words
Given a time in the format of hh:mm (12-hour format) 0 < hh < 12, 0 <= mm < 60. The task is to convert it into words as shown:Examples : Input : h = 5, m = 0 Output : five o' clock Input : h = 6, m = 24 Output : twenty four minutes past six Corner cases are m = 0, m = 15, m = 30 and m = 45. 6:00 six o'clock 6:10 ten minutes past six 6:1
7 min read
Article Tags :
three90RightbarBannerImg