I'm trying to make a program that takes a string of number words "One hundred ninety two thousand seven hundred thirty one" and turn it into the corresponding number. This is the code I have so far:
def string_to_num(text):
text = text.lower()
words = text.split()
numbers = []
output1 = []
output2 = []
output3 = []
output4 = []
hold = 1
l = 1
for current_word in words:
number = word_to_number(current_word)
numbers.append(number)
for i in range(len(numbers)):
current_num = numbers[i]
if i == len(numbers)-1:
output1.append(current_num)
continue
else:
previous_num = numbers[i-1]
if current_num > 999:
output1.append(current_num)
continue
else:
if previous_num < current_num:
output1.append(current_num * previous_num)
output1.pop(i-l)
l += 1
continue
else:
output1.append(current_num)
continue
for i in range(1, len(output1[:])):
current_num = output1[i]
previous_num = output1[i-1]
if current_num > 999:
output2.append(current_num)
continue
else:
if output1[i-1] > current_num and previous_num < 1000:
output2.append(current_num + previous_num)
continue
else:
output2.append(current_num)
print('output2', output2)
string_to_num('One hundred ninety two thousand seven hundred thirty one')
It works in the way that at the beginning, the function takes the number word and puts it through another function I have 'word_to_number()' that converts it to its corresponding number. I put all the values of numbers into a loop that gives the following result:
[1, 100, 90, 2, 1000, 7, 100, 30, 1]
The next part of the program adds makes sure the hundreds are added multiplied by the right factor. It takes the previous list and converts it into a list that looks like this:
[100, 90, 2, 1000, 700, 30, 1]
Note that the 100 and 700 are now combined.
The part that Im having trouble with is adding the numbers together and adding them to a new list, output2. The current code above produces the following list:
[190, 92, 1000, 700, 730, 31]
When it should look like this:
[192, 1000, 731]
Any Idea on how to get this working correctly? I've tried adding the numbers together and then using .pop to remove the original number from the new list, but I get the error 'Index is not in range'. Any help is greatly appreciated!