本文整理汇总了Python中pyswip.Prolog.query方法的典型用法代码示例。如果您正苦于以下问题:Python Prolog.query方法的具体用法?Python Prolog.query怎么用?Python Prolog.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyswip.Prolog
的用法示例。
在下文中一共展示了Prolog.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_issue_Unicode
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [as 别名]
def test_issue_Unicode(self):
"""
Unicode support
"""
from pyswip import Prolog, registerForeign
Prolog.assertz('отец(дима,миша)')
Prolog.assertz('отец(дима,настя)')
Prolog.assertz('отец(дима,света)')
Prolog.assertz('отец(сергей,оля)')
Prolog.assertz('отец(сергей,саша)')
results = list(Prolog.query('отец(дима,Ребенок)'))
self.assertEqual(len(results), 3)
results = list(Prolog.query('отец(Отец,Ребенок)'))
self.assertEqual(len(results), 5)
callsToHello = []
def hello(t):
callsToHello.append(t.value)
hello.arity = 1
registerForeign(hello)
p = Prolog.query("отец(дима,X), hello(X)")
result = list(p)
self.assertEqual(callsToHello, ['миша', 'настя', 'света'])
示例2: GamePL
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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: test_issue_4
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [as 别名]
def test_issue_4(self):
"""
Patch for a dynamic method
Ensures that the patch is working.
https://code.google.com/p/pyswip/issues/detail?id=4
"""
from pyswip import Prolog
Prolog.dynamic('test_issue_4_d/1')
Prolog.assertz('test_issue_4_d(test1)')
Prolog.assertz('test_issue_4_d(test1)')
Prolog.assertz('test_issue_4_d(test1)')
Prolog.assertz('test_issue_4_d(test2)')
results = list(Prolog.query('test_issue_4_d(X)'))
self.assertEqual(len(results), 4)
Prolog.retract('test_issue_4_d(test1)')
results = list(Prolog.query('test_issue_4_d(X)'))
self.assertEqual(len(results), 3)
Prolog.retractall('test_issue_4_d(test1)')
results = list(Prolog.query('test_issue_4_d(X)'))
self.assertEqual(len(results), 1)
示例4: Consultor
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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: test_issue_Unicode_consult
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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, [])
示例6: index
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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"
)
示例7: __init__
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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))
示例8: index
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [as 别名]
def index(request):
if request.method == "GET":
print "AQUI"
prolog = Prolog()
print "AQUI TAMBIEN"
#prolog.consult("recetas.pl")
print "AQUI TAMBIEN ES"
ingredientes = list(prolog.query("ingrediente(X)"))
#salida = str(ingredientes)
salida = "Hola"
return HttpResponse(salida)
示例9: find_elements
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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
示例10: pathplan
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [as 别名]
def pathplan(start,end):
prolog = Prolog()
prolog.consult('a_star_4.0.pl')
startlist=start.split('+')
len_start=len(startlist)
endlist=end.split('+')
len_end=len(endlist)
if len_start==3 and len_end==3 :
qqq = "once(path_plan1(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ "," + endlist[0] + "," + endlist[1]+ "," + endlist[2] + ",Coorlist))"
for result in prolog.query(qqq):
path = result["Coorlist"]
print path
elif len_start==3 and len_end==1 and end=='last_starter' :
qqq = "once(path_plan3(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ ",last_starter,Coorlist))"
for result in prolog.query(qqq):
path = result["Coorlist"]
print path
else :
qqq = "once(path_plan2(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ "," + end + ",Coorlist))"
for result in prolog.query(qqq):
path = result["Coorlist"]
print path
示例11: main
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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 query [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: index
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [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()
示例14: test_issue_8
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [as 别名]
def test_issue_8(self):
"""
Callbacks can cause segv's
https://code.google.com/p/pyswip/issues/detail?id=8
"""
from pyswip import Prolog, registerForeign
callsToHello = []
def hello(t):
callsToHello.append(t)
hello.arity = 1
registerForeign(hello)
prolog = Prolog()
prolog.assertz("parent(michael,john)")
prolog.assertz("parent(michael,gina)")
p = prolog.query("parent(michael,X), hello(X)")
result = list(p) # Will run over the iterator
self.assertEqual(len(callsToHello), 2) # ['john', 'gina']
self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]
示例15: Prolog
# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import query [as 别名]
from pyswip import Prolog
prolog = Prolog()
prolog.assertz("father(michael,john)")
prolog.assertz("father(michael,gina)")
result = list(prolog.query("father(michael,X)"))
print result