本文整理汇总了Python中pyswip.Prolog类的典型用法代码示例。如果您正苦于以下问题:Python Prolog类的具体用法?Python Prolog怎么用?Python Prolog使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Prolog类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:jupmorenor,项目名称:201320-modelos-2,代码行数:25,代码来源:constantes.py
示例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')
开发者ID:Ektanoor,项目名称:Vanyad,代码行数:7,代码来源:vanyad_nagcinga.py
示例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...")
开发者ID:yuce,项目名称:pyswip,代码行数:12,代码来源:money_new.py
示例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")
开发者ID:bhrzslm,项目名称:psl-notes,代码行数:12,代码来源:recursive_test.py
示例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)
开发者ID:fercs2015,项目名称:plinco-recipes,代码行数:12,代码来源:views.py
示例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
开发者ID:dksr,项目名称:REMIND,代码行数:52,代码来源:query_hyp_in_event_db.py
示例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"
)
开发者ID:otternq,项目名称:XMLQuery,代码行数:32,代码来源:views.py
示例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, [])
开发者ID:JoaoFelipe,项目名称:pyswip,代码行数:14,代码来源:test_issues.py
示例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)")
开发者ID:swenzel,项目名称:pyswip3,代码行数:15,代码来源:test_issues.py
示例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
开发者ID:dksr,项目名称:REMIND,代码行数:16,代码来源:query_hyp_in_event_db.py
示例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)")
开发者ID:isisgomez28,项目名称:JeopardyPyPro,代码行数:26,代码来源:GamePL.py
示例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()
开发者ID:yuce,项目名称:pyswip,代码行数:18,代码来源:coins_new.py
示例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)
开发者ID:wl4dek,项目名称:SistemaEspecialista_SeuTimeDoCora-o,代码行数:10,代码来源:Trabalho_Sistema_Expecialista.py
示例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)
开发者ID:vincentleest,项目名称:CSC326-Programming-Languages,代码行数:19,代码来源:Question1.py
示例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"
开发者ID:RootKitDev,项目名称:Valkyria,代码行数:19,代码来源:engine.py
示例16: index
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,代码行数:20,代码来源:views.py
示例17: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--rules", dest="rule_path", default=None)
parser.add_argument("--db-source", dest="db_path", default="postgresql://[email protected]:5432/movielens")
args = parser.parse_args()
if args.rule_path:
with open(args.rule_path, 'r') as rule_handle:
rules = [r.strip() for r in rule_handle.readlines()]
else:
rules = build_schema_rules(args.db_path)
rules.extend(register_qeds())
prolog = Prolog()
for rule in rules:
print(rule)
prolog.assertz(rule)
report_on_qeds(prolog, "movie_gross")
开发者ID:dgarant,项目名称:logic-qed,代码行数:20,代码来源:convert_schema.py
示例18: __init__
def __init__(self):
if self.band:
self.prolog = Prolog()
if not os.path.isfile('prolog/kb_recetas.pl'):
print "Generando Recetas..."
self.cargarRecetas()
print "Cargando Recetas..."
self.prolog.consult('prolog/kb_recetas.pl')
print "Cargando Querys..."
self.prolog.consult('prolog/motorinferencia.pl')
self.band = False
else:
print "Ya se cargo"
开发者ID:fercs2015,项目名称:plinco-recipes,代码行数:13,代码来源:prolog.py
示例19: test_issue_8
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,代码行数:24,代码来源:test_issues.py
示例20: __init__
class PrologAA:
def __init__(self):
self.prolog = Prolog()
self.prolog.assertz(":-use_module(library(lists))")
self.ficheiro = None
def assercao(self,texto):
if self.ficheiro is None:
self.ficheiro = open(r"f:\temp\pee.pl","w")
self.ficheiro.write(texto+ '.\n')
def query(self, texto):
if self.ficheiro is None:
self.ficheiro = open(r"f:\temp\factos_pee.pl","w")
self.ficheiro.write(texto + '.\n')
self.ficheiro.close()
return dict(V=['a','b','c'])
def procurar(self, problema):
prlg = self.prolog
objectivo = [ (x,y) for (x,y) in problema.modelo_mundo._elementos if problema.modelo_mundo._elementos[(x,y)] == 'alvo'][0]
self.assercao( "final({}/{}/G/H/V,V,C) :- C is G+H.".format( objectivo[0], objectivo[1]))
posicoes = [ (x,y) for (x,y) in problema.modelo_mundo._elementos if problema.modelo_mundo._elementos[(x,y)] != 'obst']
for (x,y) in posicoes:
self.assercao("posicao({},{})".format(x,y))
accoes=[(1,0,1), (1,1,2), (0,1,3),(-1,1,4),(-1,0,5),(-1,-1,6),(0,-1,7),(1,-1,8)]
for (x,y, z) in accoes:
self.assercao("accao({},{},{},{})".format(x,y, z/8.0 * 2.0* math.pi, math.sqrt( x**2 + y**2)))
self.problema = problema
(xi, yi) = problema.estado_inicial() #(0,1)
caminho = list(self.query("teste( V, _) :- aStar( {}/{},V, C )".format(xi, yi)))
input("Parar aqui, foi apenas usado para obter a representacao do mundo num ficheiro de factos a usar em prolog")
开发者ID:fredericoaf,项目名称:AA2014,代码行数:36,代码来源:prolog_aa.py
注:本文中的pyswip.Prolog类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论