-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSWIKB.py
49 lines (42 loc) · 1.43 KB
/
SWIKB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- coding: utf-8 -*-
from logic import KB
from pyxf import swipl
class SWIKB(KB):
'''SWI Prolog knowledge base'''
def __init__(self, sentence=None, path='swipl'):
'''Constructor method
Usage: SWIKB( sentence, path )
sentence - Prolog sentence to be added to the KB (default: None)
path - path to SWI Prolog executable (default: 'swipl')'''
self.swi = swipl(path)
if sentence:
self.tell(sentence)
def tell(self, sentence):
'''Adds sentence to KB'''
sentence = sentence.strip()
if sentence[-1] == '.':
sentence = sentence[:-1]
return self.swi.query('assert(' + sentence + ')')
def ask(self, query):
'''Queries the KB'''
return self.swi.query(query)
def retract(self, sentence):
'''Deletes sentence from KB'''
sentence = sentence.strip()
if sentence[-1] == '.':
sentence = sentence[:-1]
return self.swi.query('retract(' + sentence + ')')
def loadModule(self, module):
'''Loads module to KB
Usage: instance.loadModule( path )
path - path to module'''
self.swi.load(module)
if __name__ == '__main__':
kb = SWIKB()
kb.tell('a(b,c)')
kb.tell('a(c,d)')
kb.tell('( p(_X,_Y) :- a(_X,_Y) )')
kb.tell('( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )')
for result in kb.ask('p(X,Y)'):
print( result )
kb.retract('a(b,c)')