當前位置: 首頁>>代碼示例>>Python>>正文


Python Prolog.query方法代碼示例

本文整理匯總了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, ['миша', 'настя', 'света'])
開發者ID:JoaoFelipe,項目名稱:pyswip,代碼行數:31,代碼來源:test_issues.py

示例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)")
開發者ID:isisgomez28,項目名稱:JeopardyPyPro,代碼行數:28,代碼來源:GamePL.py

示例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)
開發者ID:swenzel,項目名稱:pyswip3,代碼行數:28,代碼來源:test_issues.py

示例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
開發者ID:jupmorenor,項目名稱:201320-modelos-2,代碼行數:27,代碼來源:constantes.py

示例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, [])
開發者ID:JoaoFelipe,項目名稱:pyswip,代碼行數:16,代碼來源:test_issues.py

示例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"
    )
開發者ID:otternq,項目名稱:XMLQuery,代碼行數:34,代碼來源:views.py

示例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))
開發者ID:brenoc,項目名稱:AI-2,代碼行數:44,代碼來源:bridge.py

示例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)
開發者ID:fercs2015,項目名稱:plinco-recipes,代碼行數:14,代碼來源:views.py

示例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
開發者ID:kutakitu,項目名稱:tshoot,代碼行數:23,代碼來源:views.py

示例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
開發者ID:ZhenshengLee,項目名稱:zsLV,代碼行數:24,代碼來源:path.py

示例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"
開發者ID:RootKitDev,項目名稱:Valkyria,代碼行數:21,代碼來源:engine.py

示例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)
開發者ID:vincentleest,項目名稱:CSC326-Programming-Languages,代碼行數:21,代碼來源:Question1.py

示例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()
開發者ID:kutakitu,項目名稱:tshoot,代碼行數:22,代碼來源:views.py

示例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'}]
開發者ID:swenzel,項目名稱:pyswip3,代碼行數:26,代碼來源:test_issues.py

示例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
開發者ID:flyfy1,項目名稱:LanguageLearn,代碼行數:9,代碼來源:pro.py


注:本文中的pyswip.Prolog.query方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。