当前位置: 首页>>代码示例>>Python>>正文


Python Prolog.assertz方法代码示例

本文整理汇总了Python中pyswip.Prolog.assertz方法的典型用法代码示例。如果您正苦于以下问题:Python Prolog.assertz方法的具体用法?Python Prolog.assertz怎么用?Python Prolog.assertz使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyswip.Prolog的用法示例。


在下文中一共展示了Prolog.assertz方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: index

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [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

示例2: test_issue_Unicode

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [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

示例3: test_issue_4

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [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: test_issue_1

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
    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,代码行数:17,代码来源:test_issues.py

示例5: main

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
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,代码行数:22,代码来源:convert_schema.py

示例6: test_issue_8

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [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

示例7: __init__

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
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,代码行数:38,代码来源:prolog_aa.py

示例8: Prolog

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [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

示例9: se

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
class se(Singleton):
    band = True

    def __init__(self):
        if self.band:
            self.prolog = Prolog()
            if not os.path.isfile('recetas.pl'):
                print "Generando Recetas..."
                self.cargarRecetas()
            print "Cargando Recetas..."
            self.prolog.consult('recetas.pl')
            print "Cargando Querys..."
            self.prolog.consult('querys.pl')
            self.band = False
        else:
            print "Ya se cargo"

	def cargarRecetas(self):
		recetario = open("recetas.pl", "w")
		header = """%====================\n% BASE DE HECHOS\n%====================\n"""
		recetario.write(header)

		# Cargar ingredientes en la Base de Conocimiento
		headerIng = """\n%--------------------\n% Ingredientes\n%--------------------\n"""
		recetario.write(headerIng)
		listaIngredientes = Ingrediente.objects.values_list('nombre',flat=True)
		bufferIng = ["ingrediente('"+x.encode('utf-8')+"').\n" for x in listaIngredientes]
		recetario.writelines(bufferIng)
		

		# Cargar Categorias en la Base de Conocimiento
		headerCat = """\n%--------------------\n% Categorias\n%--------------------\n"""
		recetario.write(headerCat)
		listaCategorias = Categoria.objects.values_list('nombre',flat=True)
		bufferCat = ["categoria('"+x.encode('utf-8')+"').\n" for x in listaCategorias]
		recetario.writelines(bufferCat)
		

		# Cargar Recetas en la Base de Conocimiento
		listaRecetas = Receta.objects.values_list('nombre','categoria')
		headerRec = """\n%--------------------\n% Recetas\n%--------------------\n"""
		recetario.write(headerRec)
		for receta in listaRecetas:
			recingr = Receta.objects.get(nombre=receta[0]).ingredientes.values_list('nombre',flat=True)
			reccat = Categoria.objects.values_list('nombre',flat=True).get(id=receta[1])
			reccant = DetalleReceta.objects.filter(receta__nombre=receta[0]).values_list('cantidad', flat=True)
			recprep = Receta.objects.get(nombre=receta[0]).preparacion
			bufferRec = "receta(\tnombre('"+receta[0]+"'),\n\tcategoria('"+str(reccat)+"'),\n\tingredientes(['"+"', '".join(recingr)+"']),\n\tcantidades(['"+"', '".join(reccant)+"']),\n\tpreparacion('"+recprep+"')\n\t).\n"
			recetario.write(bufferRec.encode('utf-8'))
		
		recetario.close()
	
	def lista_ingredientes(self):
		lista = self.prolog.query("ingrediente(X)")
		return [d['X'] for d in lista]	
		
	def hay(self,listaIngredientes):
		#listaIngr = [str(x) for x in listaIngredientes]
		hay = "hay("+str(listaIngredientes)+")"
		self.prolog.assertz(hay)
		return list(self.prolog.query("hay(X)"))

	def quePuedoHacer(self):
		return list(self.prolog.query("quePuedoHacer(Receta,Cat)"))
开发者ID:diegoxtr,项目名称:cono,代码行数:66,代码来源:prolog.py

示例10: Trabalho_Sistema_Expecialista

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
class Trabalho_Sistema_Expecialista():

    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)

    def Imprimir_Resultados(self):
        os.system('clear')
        if len(self.resultado) == 1:
            print("O esporte que você está pensando é :\n")
            for resultado in self.resultado:
                print(resultado, '\n')
            sys.exit(0)
        # else:
        #     print('''
        #         Não consegui achar o esporte mas acho 
        #         que ele está nessa lista. Não está?
        #         ''')
        #     for resultado in self.resultado:
        #         print(resultado)

    def Imprimir(self, lista):
        for esporte in lista:
            print(esporte)

    def Tamanho(self):
        print(len(self.resultado))

    def Query(self, parametro):
        lista = []
        parametro = Functor(parametro)
        query = Query(parametro(self.X))
        while query.nextSolution():
            lista.append(str(self.X.get_value()))
        query.closeQuery()

        return lista

    def Intersection(self, lista1):
        if set(lista1).intersection(self.resultado) == set():
            self.resultado = lista1
        else:
            self.resultado = set(lista1).intersection(self.resultado)
                
    def Difference(self, lista1):
        Times = set(self.resultado)
        if Times.difference(lista1) == set():
            self.resultado = lista1
        else:
            self.resultado = Times.difference(lista1)

    def Pergunta(self, pergunta, caracteristica):
        resp = input(pergunta + '\n')
        Times = self.Query(caracteristica)
        if (resp == 's' or resp == 'S'):
            self.Intersection(Times)
            return True
        else:
            self.Difference(Times)
            return False
开发者ID:wl4dek,项目名称:SistemaEspecialista_SeuTimeDoCora-o,代码行数:69,代码来源:Trabalho_Sistema_Expecialista.py

示例11: Prolog

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
"""

prolog = Prolog()


###############################################################################################################
# Directly inserts the predicates into the PrologKB via the prolog object.

nodes = ["a", "b", "c", "d", "e", "f", "g"]
edges = ["a,b", "a,c", "b,d", "b,e", "c,d", "c,f", "d,e", "d,f", "e,g", "f,g"]
costs = ["a,b,'50'", "a,c,'100'", "b,d,'40'", "b,e,'20'", "c,d,'60'", "c,f,'20'", "d,e,'50'", "d,f,'60'", "e,g,'70'",
         "f,g,'70'"]
source = ["a"]
target = ["g"]
prolog.assertz("source(" + source[0] + ")")
prolog.assertz("target(" + target[0] + ")")
# print list(prolog.query("test(A,B,C,D,E,F,G)"))
for node in nodes:
    prolog.assertz("node(" + node + ")")
for edge in edges:
    insert = "edge(" + edge + ")"
    #    print insert
    prolog.assertz(insert)
for cost in costs:
    insert = "cost(" + cost + ")"
    #    print insert
    prolog.assertz(insert)


#prolog.consult("maxflow_swipl.pl")
开发者ID:bhrzslm,项目名称:psl-notes,代码行数:32,代码来源:maxflow_swipl.py

示例12: Prolog

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
# A short Python script to demonstrate how the Prolog is meant to be used.
# Requires pyswip and a running instance of MySQL.
from pyswip import Prolog

prolog = Prolog()

prolog.consult("appraise.pl")

# A couple preliminary assertions.
prolog.assertz("value(banana, 1 rdiv 4, bitcoin)")
prolog.assertz("value(bitcoin, 1 rdiv 30, namecoin)")
prolog.assertz("value(apple, 3 rdiv 4, banana)")
prolog.assertz("value(orange, 1 rdiv 5, apple)")

# Now, how much is an orange worth in bitcoins?
result = prolog.query("appraise_float(orange, Price, bitcoin)").next()
print "An orange is worth %s bitcoins." % result["Price"]

# And how much is a bitcoin worth in apples?
result = prolog.query("appraise_float(bitcoin, Price, apple)").next()
print "A bitcoin is worth %s apples." % result["Price"]
开发者ID:ryepdx,项目名称:prolog-mysql-appraise,代码行数:23,代码来源:appraise.py

示例13: Prolog

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
from pyswip import Prolog

import cgi, cgitb 

prolog = Prolog()

prolog.consult("../data/mod2.pl")


prolog.assertz("variety(tkm12,rice)")


result = prolog.query("season(When),days(Give),avgyield(Gives),feat(With),places(Where)").next()

print "Content-type: text/html\n\n";
print '<html>';
print '<head>';
print '<meta name="author" content="Kay Vogelgesang">';
print '<link href="/xampp/xampp.css" rel="stylesheet" type="text/css">';
print '</head>';
print "<body>"
print "%s." % result["When"] 
print "%s" %result["Give"] 
print "%s." % result["Gives"]
print "%s." % result["With"] 
print "%s." % result["Where"]



print  "</body></html>";
开发者ID:harr93,项目名称:MainProj,代码行数:32,代码来源:swip.py

示例14: question_finder

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
def question_finder(question, ans):
  p = Prolog()
  p.consult('/home/jordanhudgens/code/coderprofile/survey/knowledgebase.pl')            # When placed on server, be sure to change this path!!!!
  
  # Question 1:  Type of Projects Desired to Learn
  if question == "What type of projects do you want to learn how to build?":
    p.dynamic('projectdesired/1')      ## To account for going back
    p.retractall('projectdesired(_)')  ## To account for going back
    if ans == "iPhone App":
      p.assertz('projectdesired(iphoneapp)')
    if ans == "Android App":
      p.assertz('projectdesired(androidapp)')
    if ans == "Web Application":
      p.assertz('projectdesired(webapp)') 
    if ans == "Front End Website Development":
      p.assertz('projectdesired(frontend)') 
    if ans == "just programming":
      p.assertz('projectdesired(generalprogramming)')
  
  # Question 2:  Budget
  if question == "What is your budget?":
    p.dynamic('budget/1')      ## To account for going back
    p.retractall('budget(_)')  ## To account for going back
    if ans == "$0":
      p.assertz('budget(0)')
    if ans == "$50-$250":
      p.assertz('budget(250)')
    if ans == "$251-$500":
      p.assertz('budget(500)') 
    if ans == "$501-$1000":
      p.assertz('budget(1000)')
    if ans == "$1001-$1500":
      p.assertz('budget(1500)') 
    if ans == "$1501+":
      p.assertz('budget(1000000)') 
      
  # Question 3:  Level of Education
  if question == "What is the highest level of education you've completed?":
    p.dynamic('education/1')      ## To account for going back
    p.retractall('education(_)')  ## To account for going back
    if ans == "High School":
      p.assertz('education(highschool)')
    if ans == "Associates":
      p.assertz('education(associates)')
    if ans == "Bachelors":
      p.assertz('education(bachelors)') 
    if ans == "Graduate":
      p.assertz('education(graduate)')
      
  # Question 4:  Programming Experience
  if question == "What programming experience do you have?":
    p.dynamic('experience/1')      ## To account for going back
    p.retractall('experience(_)')  ## To account for going back
    if ans == "None":
      p.assertz('experience(none)')
    if ans == "Low":
      p.assertz('experience(low)')
    if ans == "Intermediate":
      p.assertz('experience(intermediate)') 
    if ans == "Extensive":
      p.assertz('experience(extensive)')
  
  # Question 5:  Learning Priority
  if question == "What's more of a priority for you to learn?":
    p.dynamic('priority/1')      ## To account for going back
    p.retractall('priority(_)')  ## To account for going back
    if ans == "Theory of coding":
      p.assertz('priority(theory)')
    if ans == "Real life projects":
      p.assertz('priority(practical)')
  
  # Question 6:  Employment Status
  if question == "Are you currently employed full time?":
    p.dynamic('employment/1')      ## To account for going back
    p.retractall('employment(_)')  ## To account for going back
    if ans == "Yes":
      p.assertz('employment(fulltime)')
    if ans == "No":
      p.assertz('employment(none)')
  
  # Question 7:  Weekly Time Dedication
  if question == "How many hours can you dedicate to learning each week?":
    p.dynamic('hoursfree/1')      ## To account for going back
    p.retractall('hoursfree(_)')  ## To account for going back
    if ans == "5":
      p.assertz('hoursfree(5)')
    if ans == "6-10":
      p.assertz('hoursfree(10)')
    if ans == "11-20":
      p.assertz('hoursfree(20)') 
    if ans == "21-30":
      p.assertz('hoursfree(30)')
    if ans == "31-40":
      p.assertz('hoursfree(40)') 
    if ans == "40+":
      p.assertz('hoursfree(168)') 
  
  # Question 8:  Feature Driven Developer
  if question == "Do you like to see the potential features you're going to build before learning how to implement them?":
    p.dynamic('featuredriven/1')      ## To account for going back
#.........这里部分代码省略.........
开发者ID:jordanhudgens,项目名称:coderprofile,代码行数:103,代码来源:pfunctions.py

示例15: Prolog

# 需要导入模块: from pyswip import Prolog [as 别名]
# 或者: from pyswip.Prolog import assertz [as 别名]
from pyswip import Prolog

prolog = Prolog()

prolog.assertz("hello(test)")
prolog.assertz("hello(world)")

print list(prolog.query("hello(world)"))
print list(prolog.query("hello(x)"))

for result in prolog.query("hello(X)"):
    print result["X"]

print "--------------"
for result in prolog.query("retractall(hello(_))"):
    continue

for result in prolog.query("hello(X)"):
    print result["X"]

print "--------------"
开发者ID:sagitaress,项目名称:PrologChecker,代码行数:23,代码来源:test.py


注:本文中的pyswip.Prolog.assertz方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。