Je dois convertir one
en 1
, two
en 2
et ainsi de suite.
Y a-t-il un moyen de faire cela avec une bibliothèque, une classe ou autre chose?
La majorité de ce code consiste à configurer le numwords dict, ce qui n’est fait qu’au premier appel.
def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, Word in enumerate(units): numwords[Word] = (1, idx)
for idx, Word in enumerate(tens): numwords[Word] = (1, idx * 10)
for idx, Word in enumerate(scales): numwords[Word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for Word in textnum.split():
if Word not in numwords:
raise Exception("Illegal Word: " + Word)
scale, increment = numwords[Word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven")
#7100031337
Merci pour l'extrait de code ... m'a fait gagner beaucoup de temps!
J'avais besoin de gérer quelques cas d'analyse supplémentaires, tels que les mots ordinaux ("premier", "deuxième"), les mots composés ("cent") et les mots ordinaux composés comme ("cinquante-septième"), alors j'ai ajouté quelques lignes:
def text2int(textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, Word in enumerate(units): numwords[Word] = (1, idx)
for idx, Word in enumerate(tens): numwords[Word] = (1, idx * 10)
for idx, Word in enumerate(scales): numwords[Word] = (10 ** (idx * 3 or 2), 0)
ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
ordinal_endings = [('ieth', 'y'), ('th', '')]
textnum = textnum.replace('-', ' ')
current = result = 0
for Word in textnum.split():
if Word in ordinal_words:
scale, increment = (1, ordinal_words[Word])
else:
for ending, replacement in ordinal_endings:
if Word.endswith(ending):
Word = "%s%s" % (Word[:-len(ending)], replacement)
if Word not in numwords:
raise Exception("Illegal Word: " + Word)
scale, increment = numwords[Word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current`
Si quelqu'un est intéressé, j'ai piraté une version qui conserve le reste de la chaîne (bien qu'elle puisse avoir des bogues, je ne l'ai pas trop testée).
def text2int (textnum, numwords={}):
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, Word in enumerate(units): numwords[Word] = (1, idx)
for idx, Word in enumerate(tens): numwords[Word] = (1, idx * 10)
for idx, Word in enumerate(scales): numwords[Word] = (10 ** (idx * 3 or 2), 0)
ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
ordinal_endings = [('ieth', 'y'), ('th', '')]
textnum = textnum.replace('-', ' ')
current = result = 0
curstring = ""
onnumber = False
for Word in textnum.split():
if Word in ordinal_words:
scale, increment = (1, ordinal_words[Word])
current = current * scale + increment
if scale > 100:
result += current
current = 0
onnumber = True
else:
for ending, replacement in ordinal_endings:
if Word.endswith(ending):
Word = "%s%s" % (Word[:-len(ending)], replacement)
if Word not in numwords:
if onnumber:
curstring += repr(result + current) + " "
curstring += Word + " "
result = current = 0
onnumber = False
else:
scale, increment = numwords[Word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
onnumber = True
if onnumber:
curstring += repr(result + current)
return curstring
Exemple:
>>> text2int("I want fifty five hot dogs for two hundred dollars.")
I want 55 hot dogs for 200 dollars.
Il pourrait y avoir des problèmes si vous avez, par exemple, «200 $». Mais c'était vraiment difficile.
Je viens de publier un module python dans PyPI appelé Word2number dans le but exact. https://github.com/akshaynagpal/w2n
Installez-le en utilisant:
pip install Word2number
assurez-vous que votre pip est mis à jour à la dernière version.
Usage:
from Word2number import w2n
print w2n.Word_to_num("two million three thousand nine hundred and eighty four")
2003984
Voici l'approche de cas triviale:
>>> number = {'one':1,
... 'two':2,
... 'three':3,}
>>>
>>> number['two']
2
Ou cherchez-vous quelque chose qui puisse gérer "douze mille, cent soixante-douze" ?
Ceci est l'implémentation c # du code en 1ère réponse:
public static double ConvertTextToNumber(string text)
{
string[] units = new string[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
};
string[] tens = new string[] {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
string[] scales = new string[] { "hundred", "thousand", "million", "billion", "trillion" };
Dictionary<string, ScaleIncrementPair> numWord = new Dictionary<string, ScaleIncrementPair>();
numWord.Add("and", new ScaleIncrementPair(1, 0));
for (int i = 0; i < units.Length; i++)
{
numWord.Add(units[i], new ScaleIncrementPair(1, i));
}
for (int i = 1; i < tens.Length; i++)
{
numWord.Add(tens[i], new ScaleIncrementPair(1, i * 10));
}
for (int i = 0; i < scales.Length; i++)
{
if(i == 0)
numWord.Add(scales[i], new ScaleIncrementPair(100, 0));
else
numWord.Add(scales[i], new ScaleIncrementPair(Math.Pow(10, (i*3)), 0));
}
double current = 0;
double result = 0;
foreach (var Word in text.Split(new char[] { ' ', '-', '—'}))
{
ScaleIncrementPair scaleIncrement = numWord[Word];
current = current * scaleIncrement.scale + scaleIncrement.increment;
if (scaleIncrement.scale > 100)
{
result += current;
current = 0;
}
}
return result + current;
}
public struct ScaleIncrementPair
{
public double scale;
public int increment;
public ScaleIncrementPair(double s, int i)
{
scale = s;
increment = i;
}
}
J'avais besoin de quelque chose d'un peu différent car mon entrée provient d'une conversion parole-texte et la solution n'est pas toujours de faire la somme des nombres. Par exemple, "mon code postal est un deux trois quatre cinq" ne doit pas être converti en "mon code postal est 15".
J'ai pris Andrew's answer et l'ai modifié pour traiter quelques autres cas signalés comme des erreurs, et j'ai également ajouté un support pour des exemples tels que celui du code postal que j'ai mentionné ci-dessus. Certains cas de test de base sont présentés ci-dessous, mais je suis certain que des améliorations sont encore possibles.
def is_number(x):
if type(x) == str:
x = x.replace(',', '')
try:
float(x)
except:
return False
return True
def text2int (textnum, numwords={}):
units = [
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen',
]
tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
scales = ['hundred', 'thousand', 'million', 'billion', 'trillion']
ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
ordinal_endings = [('ieth', 'y'), ('th', '')]
if not numwords:
numwords['and'] = (1, 0)
for idx, Word in enumerate(units): numwords[Word] = (1, idx)
for idx, Word in enumerate(tens): numwords[Word] = (1, idx * 10)
for idx, Word in enumerate(scales): numwords[Word] = (10 ** (idx * 3 or 2), 0)
textnum = textnum.replace('-', ' ')
current = result = 0
curstring = ''
onnumber = False
lastunit = False
lastscale = False
def is_numword(x):
if is_number(x):
return True
if Word in numwords:
return True
return False
def from_numword(x):
if is_number(x):
scale = 0
increment = int(x.replace(',', ''))
return scale, increment
return numwords[x]
for Word in textnum.split():
if Word in ordinal_words:
scale, increment = (1, ordinal_words[Word])
current = current * scale + increment
if scale > 100:
result += current
current = 0
onnumber = True
lastunit = False
lastscale = False
else:
for ending, replacement in ordinal_endings:
if Word.endswith(ending):
Word = "%s%s" % (Word[:-len(ending)], replacement)
if (not is_numword(Word)) or (Word == 'and' and not lastscale):
if onnumber:
# Flush the current number we are building
curstring += repr(result + current) + " "
curstring += Word + " "
result = current = 0
onnumber = False
lastunit = False
lastscale = False
else:
scale, increment = from_numword(Word)
onnumber = True
if lastunit and (Word not in scales):
# Assume this is part of a string of individual numbers to
# be flushed, such as a zipcode "one two three four five"
curstring += repr(result + current)
result = current = 0
if scale > 1:
current = max(1, current)
current = current * scale + increment
if scale > 100:
result += current
current = 0
lastscale = False
lastunit = False
if Word in scales:
lastscale = True
Elif Word in units:
lastunit = True
if onnumber:
curstring += repr(result + current)
return curstring
Quelques tests ...
one two three -> 123
three forty five -> 345
three and forty five -> 3 and 45
three hundred and forty five -> 345
three hundred -> 300
twenty five hundred -> 2500
three thousand and six -> 3006
three thousand six -> 3006
nineteenth -> 19
twentieth -> 20
first -> 1
my Zip is one two three four five -> my Zip is 12345
nineteen ninety six -> 1996
fifty-seventh -> 57
one million -> 1000000
first hundred -> 100
I will buy the first thousand -> I will buy the 1000 # probably should leave ordinal in the string
thousand -> 1000
hundred and six -> 106
1 million -> 1000000
Cela pourrait facilement être codé en dur dans un dictionnaire si vous souhaitez analyser un nombre limité de nombres.
Pour les cas un peu plus complexes, vous souhaiterez probablement générer ce dictionnaire automatiquement, sur la base de la grammaire des nombres relativement simple. Quelque chose dans le sens de cela (bien sûr, généralisé ...)
for i in range(10):
myDict[30 + i] = "thirty-" + singleDigitsDict[i]
Si vous avez besoin de quelque chose de plus complet, il vous faudra alors des outils de traitement du langage naturel. Cet article pourrait être un bon point de départ.
Il y a une gemme Ruby de Marc Burns qui le fait. Je l'ai récemment ajouté pour ajouter du support pendant des années. Vous pouvez appeler le code Ruby à partir de python .
require 'numbers_in_words'
require 'numbers_in_words/duck_punch'
nums = ["fifteen sixteen", "eighty five sixteen", "nineteen ninety six",
"one hundred and seventy nine", "thirteen hundred", "nine thousand two hundred and ninety seven"]
nums.each {|n| p n; p n.in_numbers}
résultats:"fifteen sixteen"
1516
"eighty five sixteen"
8516
"nineteen ninety six"
1996
"one hundred and seventy nine"
179
"thirteen hundred"
1300
"nine thousand two hundred and ninety seven"
9297
Modifiez afin que text2int (scale) renvoie la conversion correcte. Par exemple, text2int ("cent") => 100.
import re
numwords = {}
def text2int(textnum):
if not numwords:
units = [ "zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion",
'quadrillion', 'quintillion', 'sexillion', 'septillion',
'octillion', 'nonillion', 'decillion' ]
numwords["and"] = (1, 0)
for idx, Word in enumerate(units): numwords[Word] = (1, idx)
for idx, Word in enumerate(tens): numwords[Word] = (1, idx * 10)
for idx, Word in enumerate(scales): numwords[Word] = (10 ** (idx * 3 or 2), 0)
ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5,
'eighth':8, 'ninth':9, 'twelfth':12}
ordinal_endings = [('ieth', 'y'), ('th', '')]
current = result = 0
tokens = re.split(r"[\s-]+", textnum)
for Word in tokens:
if Word in ordinal_words:
scale, increment = (1, ordinal_words[Word])
else:
for ending, replacement in ordinal_endings:
if Word.endswith(ending):
Word = "%s%s" % (Word[:-len(ending)], replacement)
if Word not in numwords:
raise Exception("Illegal Word: " + Word)
scale, increment = numwords[Word]
if scale > 1:
current = max(1, current)
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
Port Java rapide et sale de l'implémentation e # C_h (ci-dessus) Notez que les deux retournent double, pas int.
public class Text2Double {
public double Text2Double(String text) {
String[] units = new String[]{
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
};
String[] tens = new String[]{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
String[] scales = new String[]{"hundred", "thousand", "million", "billion", "trillion"};
Map<String, ScaleIncrementPair> numWord = new LinkedHashMap<>();
numWord.put("and", new ScaleIncrementPair(1, 0));
for (int i = 0; i < units.length; i++) {
numWord.put(units[i], new ScaleIncrementPair(1, i));
}
for (int i = 1; i < tens.length; i++) {
numWord.put(tens[i], new ScaleIncrementPair(1, i * 10));
}
for (int i = 0; i < scales.length; i++) {
if (i == 0)
numWord.put(scales[i], new ScaleIncrementPair(100, 0));
else
numWord.put(scales[i], new ScaleIncrementPair(Math.pow(10, (i * 3)), 0));
}
double current = 0;
double result = 0;
for(String Word : text.split("[ -]"))
{
ScaleIncrementPair scaleIncrement = numWord.get(Word);
current = current * scaleIncrement.scale + scaleIncrement.increment;
if (scaleIncrement.scale > 100) {
result += current;
current = 0;
}
}
return result + current;
}
}
public class ScaleIncrementPair
{
public double scale;
public int increment;
public ScaleIncrementPair(double s, int i)
{
scale = s;
increment = i;
}
}
Une solution rapide consiste à utiliser inflect.py pour générer un dictionnaire de traduction.
inflect.py a une fonction number_to_words()
, qui transformera un nombre (par exemple 2
) en son format Word (par exemple 'two'
). Malheureusement, l'inverse (qui vous permettrait d'éviter la route du dictionnaire de traduction) n'est pas proposé. Néanmoins, vous pouvez utiliser cette fonction pour créer le dictionnaire de traduction:
>>> import inflect
>>> p = inflect.engine()
>>> Word_to_number_mapping = {}
>>>
>>> for i in range(1, 100):
... Word_form = p.number_to_words(i) # 1 -> 'one'
... Word_to_number_mapping[Word_form] = i
...
>>> print Word_to_number_mapping['one']
1
>>> print Word_to_number_mapping['eleven']
11
>>> print Word_to_number_mapping['forty-three']
43
Si vous êtes prêt à vous engager, vous pourrez peut-être examiner le fonctionnement interne de la fonction number_to_words()
de inflect.py et créer votre propre code pour le faire dynamiquement (je n'ai pas essayé de le faire).