繁体   English   中英

从剪辑专家系统使用Python函数

[英]Using Python Functions From the Clips Expert System

使用PyClips,我正在尝试在Clips中构建规则,从Python解释器动态检索数据。 为此,我按照手册中的说明注册了一个外部功能。

下面的代码是问题的玩具示例。 我这样做是因为我有一个带有大量数据的应用程序,以SQL数据库的形式,我想使用Clips推理。 但是,我不想浪费时间将所有这些数据转换为Clips断言,如果我可以简单地将Clips直接“插入”Python的命名空间中。

但是,当我尝试创建规则时,我收到错误。 我究竟做错了什么?

import clips

#user = True

#def py_getvar(k):
#    return globals().get(k)
def py_getvar(k):
    return True if globals.get(k) else clips.Symbol('FALSE')

clips.RegisterPythonFunction(py_getvar)

print clips.Eval("(python-call py_getvar user)") # Outputs "nil"

# If globals().get('user') is not None: assert something
clips.BuildRule("user-rule", "(neq (python-call py_getvar user) nil)", "(assert (user-present))", "the user rule")
#clips.BuildRule("user-rule", "(python-call py_getvar user)", "(assert (user-present))", "the user rule")

clips.Run()
clips.PrintFacts()

我在PyClips支持小组上得到了一些帮助。 解决方案是确保您的Python函数返回一个clips.Symbol对象并使用(test ...)来评估规则的LHS中的函数。 使用Reset()似乎也是激活某些规则所必需的。

import clips
clips.Reset()

user = True

def py_getvar(k):
    return (clips.Symbol('TRUE') if globals().get(k) else clips.Symbol('FALSE'))

clips.RegisterPythonFunction(py_getvar)

# if globals().get('user') is not None: assert something
clips.BuildRule("user-rule", "(test (eq (python-call py_getvar user) TRUE))",
                '(assert (user-present))',
                "the user rule")

clips.Run()
clips.PrintFacts()

你的问题与(neq (python-call py_getvar user) 'None') 显然,剪辑不喜欢嵌套语句。 看起来试图在一个相等的语句中包装函数调用会带来不好的事情。 但是,当函数返回Nil或值时,您永远不会断言值。 相反,你要做的是:

def py_getvar(k):
    return clips.Symbol('TRUE') if globals.get(k) else clips.Symbol('FALSE')

然后只需更改"(neq (python-call py_getvar user) 'None')""(python-call py_getvar user)"

那应该有用。 刚刚在搞乱之前没有使用pyclips,但这应该做你想要的。

HTH!

>>> import clips
>>> def py_getvar(k):
...     return clips.Symbol('TRUE') if globals.get(k) else clips.Symbol('FALSE')

...
>>> clips.RegisterPythonFunction(py_getvar)
>>> clips.BuildRule("user-rule", "(python-call py_getvar user)", "(assert (user-
present))", "the user rule")
<Rule 'user-rule': defrule object at 0x00A691D0>
>>> clips.Run()
0
>>> clips.PrintFacts()
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM