Exemplo n.º 1
0
 def grammar_from_file(self, grammar):
     """
     Reads in a CFG from a given file, converts it to CNF and stores it in self.grammar.
     :param grammar: the file in which the grammar is stored.
     """
     self.grammar = grammar_converter.convert_grammar(
         grammar_converter.read_grammar(grammar))
Exemplo n.º 2
0
 def grammar_from_string(self, grammar):
     """
     Reads in a CFG from a string, converts it to CNF and stores it in self.grammar.
     :param grammar: the CFG in string representation.
     :return:
     """
     self.grammar = grammar_converter.convert_grammar(
         [x.replace("->", "").split() for x in grammar.split("\n")])
Exemplo n.º 3
0
    def __init__(self, sentence):
        """
        Creates a new parser object which will read in the grammar and transform it into CNF and
        then parse the given sentence with that grammar.
        :param grammar: the file path to the grammar/the string repr. of the grammar to read in
        :param sentence: the file path to the sentence/the string repr. of the sentence to read in
        """
        self.parse_table = None
        self.prods = {}
        self.grammar = grammar_converter.convert_grammar(
            grammar_converter.read_grammar("CFG.txt"))

        with open('CNF.txt', 'w') as cnf:
            for item in self.grammar:
                cnf.write("%s\n" % item)

        # self.__call__(sentence)
        with open(sentence) as inp:
            self.inputline = [line.strip() for line in inp if line.strip()]
            # this returns list

        incorrect = False
        for i in range(len(self.inputline)):
            #self.input = re.findall(r"[\w']+|[.,():=]", self.inputline[i])
            self.input = self.inputline[i].split()
            # print(self.input)
            self.parse()
            # self.print_tree2()
            start_symbol = self.grammar[0][0]
            final_nodes = [
                n for n in self.parse_table[-1][0] if n.symbol == start_symbol
            ]
            # print(final_nodes)
            if not final_nodes:
                print("Syntax error")
                print("  " + self.inputline[i])
                incorrect = True
                # break
        if not incorrect:
            print("Accepted")
Exemplo n.º 4
0
 def grammar_from_file(self, grammar):
     self.grammar = grammar_converter.convert_grammar(
         grammar_converter.read_grammar(grammar))