首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用逻辑和剪辑

使用逻辑和剪辑
EN

Stack Overflow用户
提问于 2019-01-17 00:42:42
回答 1查看 249关注 0票数 0

我修改了一些CLIPS/CLIPSpy代码,以查找CSV中的变量列是单词Oil时以及该列的持续时间超过600或更长的时候。根据我正在使用的CSV,规则应该发射两次:

我收到了以下错误。

这是我目前的代码。我认为它在变量检查或逻辑检查上失败了。

代码语言:javascript
复制
import sys
from tempfile import mkstemp
import os
import clips


CLIPS_CONSTRUCTS = """
(defglobal ?*oil-too-hot-times* = 0)

(deftemplate oil-is-too-hot-too-long
  (slot Variable (type STRING))  
  (slot Duration (type INTEGER)))

(defrule check-for-hot-oil-too-long-warning
  (oil-is-too-hot-too-long (Variable ?variable) (Duration ?duration))
  (test (?variable Oil Temp))
  (and (>= ?duration 600))
  =>
  (printout t "Warning! Check engine light on!" tab ?*oil-too-hot-times* crlf)) 

"""


def main():
    environment = clips.Environment()

    # use environment.load() to load constructs from a file
    constructs_file, constructs_file_name = mkstemp()
    file = open(constructs_file, 'wb')
    file.write(CLIPS_CONSTRUCTS.encode())
    file.close()

    environment.load(constructs_file_name)
    os.remove(constructs_file_name)

    # enable fact duplication as data has duplicates
    environment.eval("(set-fact-duplication TRUE)")


    # Template facts can be built from their deftemplate
    oil_too_hot_too_long_template = environment.find_template("oil-is-too-hot-too-long")

    for variable, duration in get_data_frames(sys.argv[1]):
        new_fact = oil_too_hot_too_long_template.new_fact()

        # Template facts are represented as dictionaries
        new_fact["Variable"] = variable
        new_fact["Duration"] = int(duration)

        # Add the fact into the environment Knowledge Base
        new_fact.assertit()

    # Fire all the rules which got activated
    environment.run()

def get_data_frames(file_path):
    """Parse a CSV file returning the dataframes."""
    with open(file_path) as data_file:
        return [l.strip().split(",") for i, l in enumerate(data_file) if i > 1]


if __name__ == "__main__":
    main()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-17 08:03:56

CLIPS采用波兰/前缀表示法。因此,您的规则应该如下所写。

代码语言:javascript
复制
(defrule check-for-hot-oil-too-long-warning
  (oil-is-too-hot-too-long (Variable ?variable) (Duration ?duration))
  (test (and (eq ?variable "Oil Temp") 
             (>= ?duration 600)))
  =>
  (printout t "Warning! Check engine light on!" tab ?*oil-too-hot-times* crlf)) 

还请注意STRING类型如何需要双引号"

然而,我建议您利用引擎的alpha网络匹配,这是更简洁和高效的。

代码语言:javascript
复制
(defrule check-for-hot-oil-too-long-warning
  (oil-is-too-hot-too-long (Variable "Oil Temp") (Duration ?duration))
  (test (>= ?duration 600))
  =>
  (printout t "Warning! Check engine light on!" tab ?*oil-too-hot-times* crlf)) 

引擎可以立即看到您的Variable插槽是一个常量,并可以相应地优化匹配逻辑。我不确定它能否在联合试验中作出同样的假设。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54227468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档