Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express a number using words in Mathematica

I heard that we can use the English words to express the number in Mathematica. Like using One hundred to express 100. Which function can do it?

like image 672
Yongwei Xing Avatar asked Feb 28 '23 08:02

Yongwei Xing


2 Answers

A solution basically equivalent to dreeves's solution (but not available at the time of his answer) would be to call WolframAlpha[] directly from Mathematica (this requires an internet connection). For example,

WolframAlpha["6 million 2 hundred and 12 thousand and fifty two", 
             {{"Input", 1}, "Plaintext"}]

returns the string

"6212052"

So we can construct the following function that returns the actual number

textToNumber[num_String] := 
 Module[{in = WolframAlpha[num, {{"Input", 1}, "Plaintext"}]},
  If[StringMatchQ[in, NumberString], ToExpression[in], $Failed]]

It also works with decimals and negative numbers, e.g., textToNumber["minus one point one"].

Note that we could ask for things other than "Plaintext" output. The easiest way to find out what's available is to enter some number, eg,WolframAlpha["twelve"], and explore the options available when you press the ⨁ signs on the right of each "pod". It is also worth exploring the documentation, where you find useful output "formats" such as "MathematicaParse" and "PodIDs".

We can also go in the other direction:

numberToText[num_Integer] := WolframAlpha[ToString[num], 
                               {{"NumberName", 1}, "Plaintext"}]

I couldn't find the right incantations to get the spoken phrase form for non-integers. If someone knows the right spell, or if W|A gains this ability, please feel free to update this answer. It's a shame that SpokenString does not have an option for reading numbers as their spoken phrases.

like image 93
Simon Avatar answered Mar 11 '23 06:03

Simon


I see that Wolfram Alpha can do that, so here's a kludgy little function that sends the English string to Wolfram Alpha and parses the result:

w2n[s_String] := ToExpression[StringCases[
  Import["http://www.wolframalpha.com/input/?i=" <> StringReplace[s, " "->"+"],
        "String"], 
  RegularExpression["Hold\\[([^\\]]*)\\]"] -> "$1"][[1]]]

Example:

w2n["two million six hundred sixty-six"]

> 2000666

Does Wolfram Alpha provide an actual API? That would be really great!

PS: They have one now but it's expensive: http://products.wolframalpha.com/api/

PPS: I notice that the wolframalpha results page changed a bit and my scraping no longer works. Some variant on that regular expression should work though.

like image 28
dreeves Avatar answered Mar 11 '23 05:03

dreeves