Python program to convert words to numbers in a text file containing English words also

1.2k Views Asked by At

I would like to use word2number from https://pypi.org/project/word2number/ to convert words to numbers in a text file to another file as output.

A similar program is available to convert numbers to words. So how do I workaround this program to suit my case.

import re
import num2words


with open('input.txt') as f_input:
    text = f_input.read()


text = re.sub(r"(\d+)", lambda x: num2words.num2words(int(x.group(0))), text)

with open('output.txt', 'w') as f_output:
    f_output.write(text)
1

There are 1 best solutions below

0
cashews On

There's definitely a more pythonic way to do this but here you go, you will need to replace word2number with the function call from the library you want to use where the parameter is a string. Also this will skip newline characters and make one big line.

lines = f_input.readlines()

nums = list()
for line in lines:
    words = line.split(' ')
    for word in words:
        nums.append(word2number(word))

with open('output.txt', 'w') as f_output:
    f_output.write(" ".join(nums))