我听说在Mathematica中可以使用英文单词来表示数字,比如使用One hundred来表示100。哪个函数可以实现这个功能?
我听说在Mathematica中可以使用英文单词来表示数字,比如使用One hundred来表示100。哪个函数可以实现这个功能?
一个基本等同于dreeves的解决方案(但在他回答时不可用)的解决方案是直接从Mathematica调用WolframAlpha[]
(这需要互联网连接)。例如,
WolframAlpha["6 million 2 hundred and 12 thousand and fifty two",
{{"Input", 1}, "Plaintext"}]
返回字符串
"6212052"
textToNumber[num_String] :=
Module[{in = WolframAlpha[num, {{"Input", 1}, "Plaintext"}]},
If[StringMatchQ[in, NumberString], ToExpression[in], $Failed]]
textToNumber["minus one point one"]
。"Plaintext"
输出之外的其他内容。找出可用选项的最简单方法是输入一些数字,例如WolframAlpha["twelve"]
,并在每个“pod”右侧按下⨁符号时探索可用选项。还值得探索文档,在其中您可以找到有用的输出“格式”,例如"MathematicaParse"
和"PodIDs"
。numberToText[num_Integer] := WolframAlpha[ToString[num],
{{"NumberName", 1}, "Plaintext"}]
我找不到适合非整数的口语表达形式的正确咒语。如果有人知道正确的咒语,或者如果 W|A 获得了这种能力,请随时更新这个答案。遗憾的是,SpokenString
没有将数字读作其口语短语的选项。
w2n[s_String] := ToExpression[StringCases[
Import["http://www.wolframalpha.com/input/?i=" <> StringReplace[s, " "->"+"],
"String"],
RegularExpression["Hold\\[([^\\]]*)\\]"] -> "$1"][[1]]]
例子:
w2n["two million six hundred sixty-six"]
> 2000666
Wolfram Alpha是否提供实际的API?那将非常棒!
PS:现在他们有了一个API,但价格很贵:http://products.wolframalpha.com/api/
PPS:我注意到wolframalpha结果页面有些变化,我的爬虫不再起作用。使用某种变体的正则表达式应该可以解决问题。
IntegerName[78372112345]
78372112345
在09年还没有可用...
SemanticInterpretation["one hundred fifty thousand three hunded and six"]
或者
Interpreter["SemanticNumber"]["one hundred fifty thousand three hunded and six"]
150306
(注意我的拼写错误并没有影响它...)
顺便说一下,这两个函数不是相同的。
SemanticInterpretation["six and forty two thousandths"]//N (* 6.042 *)
Interpreter["SemanticNumber"]["six and forty two thousandths"] (*fails*)