-1

I have sentences in which sometimes the numbers are written as words, e.g.:

He takes classes of yoga two times per week.

I need to replace numbers written as words by numbers:

He takes classes of yoga 2 times per week.

In case of He takes classes of yoga twice per week., it should be left as it is.

I found a library called word2number that converts words to numbers (link). But how can I update a sentence to get He takes classes of yoga 2 times per week.?

from word2number import w2n

w2n.word_to_num('He takes classes of yoga two times per week.')
# output: 2
Fluxy
  • 2,838
  • 6
  • 34
  • 63
  • @00: Yes, but what should I replace? How do I know that exactly `two` refers to `2`? – Fluxy Apr 29 '21 at 19:39
  • 1
    The solution from the linked Stack Overflow post has been ported to [this library](https://github.com/ShailChoksi/text2digits) – Cory Kramer Apr 29 '21 at 19:39
  • The one who closed my question and provided the link to "the answer": please READ CAREFULLY THE QUESTION. I asked how to replace the word in the sentence and return the sentence. I did not ask how to replace any isolate word with the number. – Fluxy Apr 29 '21 at 19:42
  • @Fluxy Read the linked answer carefully :) There is that [exact solution](https://stackoverflow.com/a/38760564/2296458) in the link – Cory Kramer Apr 29 '21 at 19:43
  • @CoryKramer And what happens if "He takes classes of yoga Two times per week"?:) – Fluxy Apr 29 '21 at 19:45
  • @CoryKramer: `text2digits` helps, but the link to the answer does not help. It is not flexible at all. – Fluxy Apr 29 '21 at 19:47
  • we can only hold your hand so much. you have been provided a solution, either use it or solve the problem yourself. You show no attempt at even solving this yourself. – Cory Kramer Apr 29 '21 at 19:48
  • @CoryKramer: Is it `w2n.word_to_num` no attempt? Anyway, thanks. – Fluxy Apr 29 '21 at 19:50

1 Answers1

0

This should handle arbitrary multi-word numbers. It won't handle end-of-sentence punctuation, like "The number of the beast is six hundred sixty-six.". You might want to strip punctuation first. I suppose the same would happen with a comma in the middle of a sentence.

def translate(sentence):
    result = []
    partial = []
    for word in sentence.split():
        partial.append(word)
        num = w2n.word_to_num(' '.join(partial))
        # If this worked, then go try to suck up another word.
        if num:
            continue
        # If there's more than one word in partial, then all but the
        # last make a successful number.
        if len(partial) > 1:
            result.append( w2n.word_to_num(' '.join(partial{[:-1]) ))
        result.append( word )
        partial = []
    return ' '.join(result)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Right. There is no solution for that, because you can't tell whether they wanted 25 or 20 5. Most people would write "twenty-five", but admittedly not for larger numbers. – Tim Roberts Apr 29 '21 at 19:51