Pyke学习系列(pyke基础执行)(一)
from pyke import knowledge_engine
from pyke import goaldef main():# 创建一个知识引擎,并加载规则engine = knowledge_engine.engine(__file__)# 使用规则进行推理engine.activate('fc_related')engine.get_kb('family').dump_specific_facts()#engine.get_kb('family').dump_universal_facts()# engine.add_universal_fact('family', 'son_of', ('bruce', 'thomas'))# print(engine.assert_('family', 'father_son', ('thomas', 'bruce')))# engine.assert_('family', 'son_of', ('fred', 'thomas'))# results = engine.prove_1_goal('fc_related.father_son($father, $son, ())')# results = engine.prove_1_goal('fc_related.father_son($father, $son, ())',son='bruce')# results = engine.prove_1_goal('fc_related.father_son($father, $son)', father='thomas')# results = engine.prove_1_goal('fc_related.father_son($father, david_b)')# results = engine.prove_goal('fc_related.father_son($father,$son, ())')# 打印推理结果# print(results)"""with engine.prove_goal('fc_related.father_son(thomas, $son)') as gen:for vars, plan in gen:print(vars['son'])"""my_goal = goal.compile('fc_related.father_son($father, $son)')father_name = 'arthur2'with my_goal.prove(engine, father=father_name) as gen:for vars, plan in gen:print(vars['son'])engine.reset()print("#end#")if __name__ == '__main__':main()
此外还需要创建并加载一个事实库(family.kfb文件)
son_of(bruce, thomas) son_of(fred_fa, thomas) son_of(tim, thomas) son_of(arthur3, arthur2) son_of(ed2, arthur2) son_of(david_b2, arthur2) son_of(md_thomas, bruce) son_of(david_fa, bruce)
以及一个规则库(fc_related.krb文件)
direct_father_sonuse father_son($father, $son)whenfamily.son_of($son, $father)