我听说在 Mathematica 中我们可以用英文单词来表达数字。就像用一百来表示100。哪个函数可以做到?
4 回答
一个基本上等同于 dreeves 解决方案的解决方案(但在他回答时不可用WolframAlpha[]
)是直接从 Mathematica 调用(这需要互联网连接)。例如,
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
没有将数字作为口语来阅读的选项。
我看到 Wolfram Alpha 可以做到这一点,所以这是一个笨拙的小函数,它将英文字符串发送到 Wolfram Alpha 并解析结果:
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:他们现在有一个,但很贵:http ://products.wolframalpha.com/api/
PPS:我注意到 wolframalpha 结果页面发生了一些变化,我的抓取不再有效。该正则表达式的一些变体应该可以工作。
这是代码:
IntegerName[78372112345]
这是输出:
780 亿 3.72 亿 11.2 万 345
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*)