w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Parsing string text to num in spanish grammar

You can achieve this by doing some modifications to text2num library: https://github.com/ghewgill/text2num

import re

Small = {
    'cinco': 5,
    'veinticuatro': 24,
    'treinta': 30,
    'ciento': 100,
    'ochocientos': 800
}


Magnitude = {
    'mil':          1000
}

class NumberException(Exception):
    def __init__(self, msg):
        Exception.__init__(self, msg)

def text2num(s):
    a = re.split(r"[s-]+", s.lower())
    n = 0
    g = 0
    for w in a:
        if w == 'y':
           continue
        x = Small.get(w, None)
        if x is not None:
            g += x
        else:
            x = Magnitude.get(w, None)
            if x is not None:
                n += g * x
                g = 0
            else:
                raise NumberException("Unknown number: "+w)
    return n + g

if __name__ == "__main__":
    assert 124835 == text2num('Ciento Veinticuatro Mil Ochocientos Treinta
y Cinco')




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.