本文整理汇总了Python中pyswip.Prolog类的典型用法代码示例。如果您正苦于以下问题:Python Prolog类的具体用法?Python Prolog怎么用?Python Prolog使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Prolog类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Consultor
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
示例2: ConnectProlog
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')
示例3: main
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...")
示例4: test_swipl
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")
示例5: index
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)
示例6: query_hyp_in_event_db
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
示例7: index
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"
)
示例8: test_issue_Unicode_consult
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: test_issue_1
def test_issue_1(self):
"""
Segmentation fault when assertz-ing
Notes: This issue manifests only in 64bit stacks (note that a full 64
bit stack is needed. If running 32 in 64bit, it will not happen.)
http://code.google.com/p/pyswip/issues/detail?id=1
"""
# The simple code below should be enough to trigger the issue. As with
# issue 13, if it does not work, it will segfault Python.
from pyswip import Prolog
prolog = Prolog()
prolog.assertz("randomTerm(michael,john)")
示例10: query_hyp_in_video_db
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
示例11: GamePL
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)")
示例12: main
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()
示例13: __init__
def __init__(self):
self.prolog = Prolog()
self.X = Variable()
self.resultado = ['corinthians', 'atletico_mg', 'gremio', 'santos', 'sao_paulo', 'palmeiras', 'flamengo', 'internacional', 'ponte_preta', 'sport', 'fluminense', 'atletico_pr', 'cruzeiro', 'chapecoense', 'figueirense', 'avai', 'coritiba', 'goias', 'vasco', 'joinville', 'botafogo']
arquivo_pl = open('jogos.pl')
for linha in arquivo_pl.readlines():
if linha[len(linha) - 1] == '\n':
linha = linha.replace("\n", "")
self.prolog.assertz(linha)
示例14: solveSudoku
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)
示例15: main
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"