Home > Back-end >  How do I convert a English phrasing of a number(string) to integer in Python?
How do I convert a English phrasing of a number(string) to integer in Python?

Time:10-28

Write a Python program that takes an English phrasing of a number as a string s and outputs the corresponding integer x. You can assume the number is positive and less than 1,000,000. You can also assume that the s is always correct. s does not contain any spaces.

So far, I have my dictionary

'# ones

num2words = {'one': '1', 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':'7', 'eight':8, 'nine':9}

'# tens

num2words.update ({'ten':10, 'eleven':11, 'twelve':12, 'thirteen':13, 'fourteen':14, 'fifteen':15, 'sixteen':16, 'seventeen':17, 'eighteen':18, 'nineteen':19})

'# twenty-ninety

num2words.update ({'twenty':'20', 'thirty': '30', 'fourty':40, 'fifty':50, 'sixty':60, 'seventy':70, 'eighty':80, 'ninety':90})

'# hundred, thousand, million, zero

num2words.update ({'hundred':'100', 'thousand':1000, 'million':1000000, 'zero':0})

and I don't know how to get started with writing this program. I've looked up examples, but the strings usually have a space or dash separating them for example (twenty-seven or twenty seven) instead of (twentyseven or onehundredfiftysixthousandthreehundredtwentyseven) just some guidance in how to start my program would be greatly appreciated.

CodePudding user response:

not sure whether helps: maybe using regex to search whether key matches? then twenty-seven and 'twenty seven' would match key twentyseven

import re

txt = "twenty seven"
txt = "twenty-seven"
x = re.search("twenty.*seven", txt)
print(x)

CodePudding user response:

This module https://pypi.org/project/word2number/ can help you. It turns words into digits and back.

  • Related