Exemplo n.º 1
0
    def parse(str_rule):
        # Example: daughter(Person, Parent) :- female(Person), parent(Parent, Person).
        str_rule = str_rule.strip().rstrip('.').replace(' ', '')
        idx = str_rule.find(':-')

        conclusion = Fact.parse(str_rule[:idx])
        premises = []
        list_fact = str_rule[idx + 2:].split('),')

        for idx, str_fact in enumerate(list_fact):
            if idx != len(list_fact) - 1:
                str_fact += ')'
            fact = Fact.parse(str_fact)
            premises.append(fact)

        return Rule(conclusion, premises)
Exemplo n.º 2
0
def process(file, isInput = False):
    global knowledgeBase, infertype
    cmds = []
    while True:
        if isInput:
            sys.stdout.write('? ' if len(cmds) == 0 else '|    ')
            sys.stdout.flush()
        line = file.readline()
        if line == "": break
        s = re.sub("#.*", "", line[:-1]) # ignore comments
        s = re.sub(" ", "", s) # remove white spaces
        if s == "": continue
        if s[-1] == '.': 
            s=s[:-1]
            cmds.append(s)
        # if punc == '.': print(s)
            for cmd in cmds:
                if cmd == "": continue
                if cmd == 'printKB':
                    print(knowledgeBase)
                elif cmd == 'halt': sys.exit(0)
                else: 
                    if isInput:
                        if (infertype == Inferring.FORWARD.value):
                            print(fol_fc_ask(knowledgeBase, Fact.parse(cmd)))
                        elif (infertype == Inferring.BACKWARD.value):
                            bc = BackwardChaining(knowledgeBase, Fact.parse(cmd))
                            print(bc.answer())
                        elif (infertype == Inferring.RESOLUTION.value):
                            print(resolution_search(knowledgeBase, Fact.parse(cmd)))
                    else:
                        if (cmd.find(":-") == -1):
                            knowledgeBase.appendFact(Fact.parse(s))
                        else:
                            knowledgeBase.appendRule(Rule.parse(s))
            cmds = []
        else: cmds.append(s)
    if not isInput:
        file.close()