CLIPS新手入门:如何使用Python与clipspy为fact添加自动计数属性
实现方案
方案1:Python侧维护计数器(新手友好)
直接在Python层维护自增变量,给person模板新增计数slot,断言fact时传入当前计数值即可,逻辑简单易理解。
import clips # 给person模板新增id slot存储计数 template_string = """ (deftemplate person (slot id (type INTEGER)) (slot name (type STRING)) (slot surname (type STRING))) """ # 维护自增计数器 fact_counter = 1 person_dicts = [ {'name': 'John', 'surname': 'Doe'}, {'name': 'Jane', 'surname': 'Smith'} ] env = clips.Environment() env.build(template_string) template = env.find_template('person') for person_info in person_dicts: # 传入当前计数,断言后计数器自增 person_info['id'] = fact_counter template.assert_fact(**person_info) fact_counter += 1 env.run() for fact in env.facts(): print(fact)
运行输出示例:
(initial-fact) (person (id 1) (name "John") (surname "Doe")) (person (id 2) (name "Jane") (surname "Smith"))
方案2:CLIPS规则自动计数(无需Python层维护变量)
通过CLIPS原生规则实现自动计数,新增专门存储当前计数的fact,每次新的person fact未赋值id时,规则自动填充id并更新计数,适合批量断言fact的场景。
import clips template_string = """ (deftemplate person (slot id (type INTEGER) (default ?NONE)) ; 初始不赋值,由规则自动填充 (slot name (type STRING)) (slot surname (type STRING))) ; 计数模板,存储当前最新的fact序号 (deftemplate fact-counter (slot value (type INTEGER))) ; 自动赋值id的规则 (defrule assign-person-id ?counter <- (fact-counter (value ?current_id)) ?person <- (person (id ?NONE)) => (modify ?person (id ?current_id)) (modify ?counter (value (+ ?current_id 1)))) """ person_dicts = [ {'name': 'John', 'surname': 'Doe'}, {'name': 'Jane', 'surname': 'Smith'} ] env = clips.Environment() env.build(template_string) # 初始化计数器,第一条fact序号为1 env.assert_string('(fact-counter (value 1))') template = env.find_template('person') for person_info in person_dicts: template.assert_fact(**person_info) env.run() for fact in env.facts(): print(fact)
运行输出和方案1完全一致。
内容的提问来源于stack exchange,提问作者ANA
相关产品推荐
相关产品推荐

