我有一个使用 Java 运行的家庭自动化系统,我想添加简单的数学功能,例如加法、减法、乘法、除法、求根和幂。
在系统当前状态下,它可以将短语转换为标签,如下例所示:
例子:
Phrase: "what is one hundred twenty two to the power of seven"
Tagged: {QUESTION/math} {NUMBER/122} {MATH/pwr} {NUMBER/7}
Run Code Online (Sandbox Code Playgroud)
例子:
Phrase: "twenty seven plus pi 3 squared"
Tagged: {NUMBER/27} {MATH/add} {NUMBER/3.14159} {MATH/multiply} {MATH/pwr} {NUMBER/2}
Run Code Online (Sandbox Code Playgroud)
这个例子可以很容易地转换成这样的:
27 + 3.14159 * 3^2
Run Code Online (Sandbox Code Playgroud)
每个标签都是一个可以查询其值的对象。
编辑:具体问题:
所以现在我需要一种方法来读取该组标签作为方程,并返回数值结果。作为最后的手段,我可以使用谷歌或 Wolfram alpha,但这会更慢,而且我正在努力保持自动化系统完全独立。
如果您想查看完整的源代码,可以在 github 中找到。 请注意,我还没有提交最后的一些更改,因此我给出的示例中的一些与数学相关的内容将不起作用。
我需要一本可以做到这一点的字典:
Dictionary properties = new Dictionary();
properties.Add<PhysicalLogic>(new Projectile(velocity));
// at a later point
PhysicalLogic logic = properties.Get<PhysicalLogic>();
Run Code Online (Sandbox Code Playgroud)
我发现这篇文章与我想要的内容相似,但不完全相同。
Unity3D 使用他们的GetComponent<>()方法来完成它,所以它应该是可能的:http :
//docs.unity3d.com/Documentation/ScriptReference/GameObject.GetComponent.html
(单击“JavaScript”下拉列表以查看 C# 版本)
正则表达式:
"-[0-9]{0,}"
Run Code Online (Sandbox Code Playgroud)
串:
"-abc"
Run Code Online (Sandbox Code Playgroud)
根据这里的测试,这不应该发生.我假设我在代码中做错了.
码:
public static void main(String[] args) {
String s = "-abc";
String regex = "-[0-9]{0,}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
if (matcher.group().length() == 0)
break;
// get the number less the dash
int beginIndex = matcher.start();
int endIndex = matcher.end();
String number = s.substring(beginIndex + 1, endIndex);
s = s.replaceFirst(regex, "negative " + number);
}
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
一些上下文:我使用的语音合成程序不能发出带有前导负号的数字,因此必须用"否定"一词替换.