pythonclipsclipspy

CLIPS Beginner: How to add Python dictionary data into CLIPS facts using clipspy


I want to add facts using clipspy from dictionary in python (Dict to fact). But so far I am unable to do so. I am getting syntax errors as I am beginner to Clips rules and facts coding. Thank you in advance if anyone can help me resolve this problem. Following is my code:

import clips
template_string = """
(deftemplate person
  (slot name (type STRING))
  (slot surname (type STRING)))
"""
Dict = {'name': 'John', 'surname': 'Doe' }

env = clips.Environment()
env.build(template_string)

template = env.find_template('person')
parstr = """(name%(name))(surname%(surname))"""%Dict
fact = template.assert_fact(parstr)
assert_fact = fact
env.run()
for fact in env.facts():
    print(fact)

This is the error I am having:

  Traceback (most recent call last):
  File "/home/aqsa/Clips/example2.py", line 13, in <module>
    parstr = """(name%(name))(surname%(surname))"""%Dict
ValueError: unsupported format character ')' (0x29) at index 12

Solution

  • You are asserting a fact as a string but the Template assert_fact expects a list of keyword arguments as per the documentation and the examples.

    template.assert_fact(name='John', surname='Doe')
    

    or

    template.assert_fact(**Dict)  # kwargs expansion
    

    You can also assert facts as strings but it's a bit slower due to the fact the engine has to interpret them.

    env.assert_string('(person (name "John") (surname "Doe"))')