使用 Clips 专家系统中的 Python 函数
-
15-09-2020 - |
题
使用 PyClips,我尝试在 Clips 中构建规则,从 Python 解释器动态检索数据。为此,我注册了一个外部函数,如下所示 手册.
下面的代码是该问题的一个玩具示例。我这样做是因为我有一个应用程序,其中包含大量数据(采用 SQL 数据库的形式),我想使用 Clips 对其进行推理。但是,如果我可以简单地将 Clips 直接“插入”Python 的命名空间,那么我不想浪费时间将所有这些数据转换为 Clips 断言。
但是,当我尝试创建规则时,出现错误。我究竟做错了什么?
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对象并使用(测试......)来评估规则LH中的函数。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')
. 。显然 Clips 不喜欢嵌套语句。看来尝试将函数调用包装在相等语句中会带来不好的结果。但是,无论如何,您都不会断言该值,因为您的函数返回 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,但这应该可以满足您的要求。
哈!
>>> 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()
>>>
不隶属于 StackOverflow