问题描述
使用Go(golang)我想要一个带有公式的字符串并用预定义的值对其进行评估。这里有一种方法可以用python的 parser
模块来完成它: x = 8
code = parser.expr((x + 2)/ 10)。compile()
print eval(code)
#print 1
解决方案 > 您可能需要求助于一个解释数学语句或必须编写自己的解析器的库。作为一种动态语言的Python可以在运行时解析和执行python代码。 Standard Go无法做到这一点。
如果您想自己编写解析器,那么go软件包会有帮助。示例():
b $ b $ go
$ go
$ go
$ go b
$ {
fs:= token.NewFileSet()
tr,_:= parser.ParseExpr((3-1)* 5)
ast.Print(fs,tr)
$ b 然后可以按照您的选择遍历和解释生成的AST(抽象语法树)(例如,处理'+'令牌作为现在存储的值的补充)。
Using Go (golang) I'd like to take a string with a formula and evaluate it with pre-defined values. Here's a way to do it with python's parser
module:
x = 8
code = parser.expr("(x + 2) / 10").compile()
print eval(code)
# prints 1
Any idea how to do it with Go?
解决方案 You will probably need to resort to a library that interprets math statements or have to write your own parser. Python being a dynamic language can parse and execute python code at runtime. Standard Go cannot do that.
If you want to write a parser on your own, the go package will be of help. Example (On play):
import (
"go/ast"
"go/parser"
"go/token"
)
func main() {
fs := token.NewFileSet()
tr, _ := parser.ParseExpr("(3-1) * 5")
ast.Print(fs, tr)
}
The resulting AST (Abstract Syntax Tree) can then be traversed and interpreted as you choose (handling '+' tokens as addition for the now stored values, for example).
这篇关于在Go中评估公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!