本文整理汇总了Python中pyswip.Prolog.consult方法的典型用法代码示例。如果您正苦于以下问题:Python Prolog.consult方法的具体用法?Python Prolog.consult怎么用?Python Prolog.consult使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyswip.Prolog
的用法示例。
在下文中一共展示了Prolog.consult方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: index
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def index(request, table):
import MySQLdb as db
conn = db.connect(host='localhost', user='prologuser', passwd='prologpass', db='prolog_test')
cursor = conn.cursor()
cursor.execute('SELECT * FROM `children`')
result = cursor.fetchall()
prolog = Prolog()
for row in result:
prolog.assertz("father("+ row[1] +","+ row[2] +")")
prolog.consult('family')
prolog.assertz("father(michael,john)")
prolog.assertz("father(michael,gina)")
father = list(prolog.query("father(Y, X)"))
#return HttpResponse(response, mimetype="application/xml")
t = loader.get_template('index/select.html')
c = RequestContext(request, {'table': table, 'father': father})
return HttpResponse(
t.render(c),
mimetype="application/xml"
)
示例2: GamePL
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
class GamePL(object):
def __init__(self):
self.prolog = Prolog()
self.prolog.consult("pl/GameDatabase.pl")
self.prolog.consult("pl/GameLogic.pl")
def nuevoJugador(self, name):
None
def actualizaPuntuacion(self, jugador, puntos):
None
def borrarMemoria(self):
None
def getPuntuacion(self, jugador):
None
def getCategorias(self):
return self.prolog.query("categoria(Categoria, Descripcion)")
def getPreguntas(self):
return self.prolog.query("pregunta(Numero, Pregunta, Categoria, Puntos)")
def getRespuestas(self):
return self.prolog.query("respuesta(Numero, Respuesta)")
示例3: ConnectProlog
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
class ConnectProlog(ConnectLivestatus):
"""As it is senseless to call Prolog without starting a connection to Nagios/Icinga, this module does it."""
def __init__(self):
prolog=None
ConnectLivestatus.__init__(self)
self.prolog=Prolog()
self.prolog.consult('vanyad.pl')
示例4: Consultor
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
class Consultor(object):
"""Clase que implementa el mecanismo de consultas a la base de conocimientos usando Prolog"""
def __init__(self, consulta):
self.consultor = Prolog()
self.consultor.consult(os.path.join(settings.MEDIA_ROOT, 'colombianCrush.pl').replace('\\','/'))
self.consulta = consulta
self.resultado = []
def buscarSugerencia(self):
"""Genera la respuesta a la consulta de una sugerencia de movimiento para el jugador"""
return self._validarConsulta(self.consultor.query("buscarSugerencia(X, " + self.consulta + ")"))
def buscarPosibilidad(self):
"""Genera la respuesta a la consulta de una posibilidad de destruccion de figuras"""
return self._validarConsulta(self.consultor.query("buscarPosibilidad(X, " + self.consulta + ")"))
def _validarConsulta(self, consulta):
"""Metodo interno que extrae el menor valor obtenido de Prolog al consultar la base de conocimiento"""
for valor in consulta:
self.resultado.append(valor["X"])
if len(self.resultado)>PASIVO:
return min(self.resultado)
else:
return PASIVO
示例5: main
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def main():
letters = "S E N D M O R Y".split()
prolog = Prolog()
sendmore = Functor("sendmore")
prolog.consult("money.pl")
X = Variable()
call(sendmore(X))
r = X.value
for i, letter in enumerate(letters):
print(letter, "=", r[i])
print("That's all...")
示例6: test_swipl
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def test_swipl(self):
from pyswip import Prolog
from reloop.languages.rlp.logkb import PrologKB
prolog = Prolog()
prolog.consult("../examples/RLP/maxflow_swipl.pl")
logkb = PrologKB(prolog)
# BlockGrounding not supported yet
grounder = RecursiveGrounder(logkb)
solver = CvxoptSolver()
model = maxflow_example.maxflow(grounder, solver)
self.assertEqual(model, 0, "SWI-Prolog Recursive Failed")
示例7: query_hyp_in_event_db
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def query_hyp_in_event_db(hyp, event_db_file):
prolog = Prolog()
str2num_file = '/home/csunix/visdata/cofriend/sandeep/Dropbox/code/my_code/trunk/python/cofriend/str2num.pl'
prolog.consult(str2num_file)
print 'Reading event database ...'
all_prolog_modules = pickle.load(open(event_db_file))
(modeh, modeb) = all_prolog_modules['modes']
pos_ex = all_prolog_modules['pos_ex']
test_pos_ex = all_prolog_modules['test_pos_ex']
pos_prolog_modules = all_prolog_modules['pos']
neg_prolog_modules = all_prolog_modules['neg']
test_prolog_modules = all_prolog_modules['test']
pos_event_dbs = []
neg_event_dbs = []
print 'Asserting pos prolog modules ...'
for vid in pos_prolog_modules:
for i in xrange(len(pos_prolog_modules[vid])):
pos_prolog_module = pos_prolog_modules[vid][i][0]
pos_prolog_blanket = pos_prolog_modules[vid][i][1]
pos_event_dbs.append(pos_prolog_module)
assert_blanket_to_prolog_str_int(pos_prolog_blanket, prolog, pos_prolog_module)
print 'Asserting neg prolog modules ...'
for vid in neg_prolog_modules:
for i in xrange(len(neg_prolog_modules[vid])):
neg_prolog_module = neg_prolog_modules[vid][i][0]
neg_prolog_blanket = neg_prolog_modules[vid][i][1]
neg_event_dbs.append(neg_prolog_module)
assert_blanket_to_prolog_str_int(neg_prolog_blanket, prolog, neg_prolog_module)
print 'num of pos: ' + repr(len(pos_event_dbs))
print 'num of neg: ' + repr(len(neg_event_dbs))
print 'Querying in pos prolog modules ...'
t0 = time.clock()
print time.asctime()
for i in xrange(100000):
pos_cover = hyp.pyswip_covers(prolog, pos_event_dbs, True, False, neg=0)
print time.asctime()
pos_eval_time = (time.clock() - t0)
print 'Querying in neg prolog modules ...'
t0 = time.clock()
print time.asctime()
for i in xrange(100000):
neg_cover = hyp.pyswip_covers(prolog, neg_event_dbs, True, False, neg=1)
print time.asctime()
neg_eval_time = (time.clock() - t0)
print pos_eval_time
print neg_eval_time
示例8: test_issue_Unicode_consult
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def test_issue_Unicode_consult(self):
"""
Unicode support
"""
from pyswip import Prolog
Prolog.consult('unicode.pl')
result = list(Prolog.query('мать(Мать,Ребенок)'))
k = len(result)
self.assertEqual(k, 2)
result = list(Prolog.query('дочь(света,саша)'))
self.assertEqual(result, [])
result = list(Prolog.query('дочь(света,аня)'))
self.assertNotEqual(result, [])
示例9: query_hyp_in_video_db
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def query_hyp_in_video_db(hyps, video_db):
prolog = Prolog()
str2num_file = '/home/csunix/visdata/cofriend/sandeep/Dropbox/code/my_code/trunk/python/cofriend/str2num.pl'
prolog.consult(str2num_file)
print 'Asserting the database ...'
assert_blanket_to_prolog_str_int(video_db, prolog, 'vid_db')
result = {}
for event in hyps:
result[event] = []
print 'Querying in the video for event: ' + event
for hyp in hyps[event]:
pos_cover = hyp.pyswip_covers(prolog, [('vid_db',video_db)], True, False, neg=0)
result[event].append(pos_cover)
return result
示例10: main
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def main():
prolog = Prolog()
prolog.consult("coins.pl")
count = int(input("How many coins (default: 100)? ") or 100)
total = int(input("What should be the total (default: 500)? ") or 500)
coins = Functor("coins", 3)
S = Variable()
q = Query(coins(S, count, total))
i = 0
while q.nextSolution():
## [1,5,10,50,100]
s = zip(S.value, [1, 5, 10, 50, 100])
print(i, end=" ")
for c, v in s:
print("%dx%d" % (c,v), end=" ")
print()
i += 1
q.closeQuery()
示例11: main
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def main():
mod = sys.argv[1]
what = sys.argv[2]
who = sys.argv[3]
find = False
prolog = Prolog()
prolog.consult(mod)
for soln in prolog.query("%s(X,%s)" % (what, who)):
if what == 'pere' :
print soln["X"], "est le %s de %s" % (what, who)
else :
print soln["X"], "est la %s de %s" % (what, who)
find = True
if not find:
print "Je suis désolé, je ne dispose pas des informations requise pour vous répondre. Souhaitez-vous que jeffectue une recherche sur Internet"
示例12: solveSudoku
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def solveSudoku(sudokuString):
print "in solve"
answerString = ""
prolog = Prolog()
prolog.consult('sudokusolver.pl')
queryString = "Puzzle = [" + sudokuString + "], Puzzle = [A,B,C,D,E,F,G,H,I], sudoku([A,B,C,D,E,F,G,H,I]). "
#queryString = queryS
res = list(prolog.query(queryString, maxresult=1))
print res
if not res:
#results is empty
return "Invalid Sudoku"
else:
final = []
cols = ["A","B","C","D","E","F","G","H","I"]
for col in cols:
final.append(" ".join(map( str,res[0][col])))
return "<br>".join(final)
示例13: __init__
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
class Bridge:
def __init__(self):
self.prolog = Prolog()
self.prolog.consult('facts.pl')
self.prolog.consult('logic/agent.pl')
def best_action(self):
actions = list(self.prolog.query('best_action(Action, Arg1, Arg2)', maxresult=1))
if len(actions) > 0:
return actions[0]
else:
return None
def assertz(self, what):
return list(self.prolog.query("assertz(%s)" % what))
def retract(self, what):
return list(self.prolog.query("retract(%s)" % what))
def retractall(self, what):
return list(self.prolog.query("retractall(%s)" % what))
def assert_perceptions(self, perceptions, x, y):
for p in perceptions.keys():
self.retract("percept_%s(%d, %d)" % (p, x, y))
if perceptions[p] == True:
self.assertz("percept_%s(%d, %d)" % (p, x, y))
def assert_on(self, x, y):
self.retractall('on(X, Y)')
self.retract('visited(%d, %d)' % (x, y))
self.assertz('on(%d, %d)' % (x, y))
self.assertz('visited(%d, %d)' % (x, y))
self.retract('connex(%d, %d)' % (x, y))
self.assertz('connex(%d, %d)' % (x, y))
def assert_energy(self, e):
self.retractall('energy(E)')
self.assertz('energy(%d)' % e)
def assert_attacked(self, x, y):
self.assertz('attacked(%d, %d)' % (x, y))
示例14: index
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def index():
bs = BaseHandler()
dt = None
sol2 = None
error = None
form = HelpForm()
if form.validate_on_submit():
bsg = bs.big_suggest(str(form.quiz.data))
sol2 = bs.find_elements(bsg)
try:
from pyswip import Prolog
prolog = Prolog()
prolog.consult("kb.txt")
# prolog.assertz("father(michael,gina)")
# prolog.assertz("father(michael,john)")
dt = list(prolog.query("elements(X)"))
# sol2 = list(prolog.query("battery(hot,X)"))
except Exception,e:
error = e
traceback.print_exc()
示例15: find_elements
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import consult [as 别名]
def find_elements(self,long_string):
elements = []
solution = []
arr = long_string.strip().split(" ")
arr_len = len(arr)
from pyswip import Prolog
prolog = Prolog()
prolog.consult("kb.txt")
for x in xrange(arr_len):
q = list(prolog.query("elements(%s)"%arr[x]))
if len(q) > 0:
s = list(prolog.query("problem(%s,X)"%arr[x]))
kw = [x['X'] for x in s]
for k in kw:
if arr.__contains__(k):
solution.append(list(prolog.query("solution(%s,Y)"%k)))
for h in solution:
if len(h) > 0:
for j in h:
elements.append(j['Y'])
return elements