-4

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)
rawwar
  • 4,834
  • 9
  • 32
  • 57
Ram
  • 1
  • 1
  • The package you are referring to does not currently provide that kind of functionality. It only works properly (most of the times, see github issue list) if you pass it a string that *only* contains the number word. If the number word is embedded in more text, the rest of the text gets removed. – NOhs Jul 29 '18 at 15:20
  • Yes. Thanks for the update – Ram Jul 29 '18 at 16:41

1 Answers1

0

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))
MrSmile
  • 1,217
  • 2
  • 12
  • 20
cashews
  • 26
  • 3