forked from sanya28wd/Python-Compiler-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnltk_parser.py
More file actions
75 lines (55 loc) · 1.62 KB
/
nltk_parser.py
File metadata and controls
75 lines (55 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import nltk
from nltk import CFG
from nltk.parse import EarleyChartParser
grammar_string = """
Program -> StmtList
StmtList -> Stmt StmtList | Stmt
Stmt -> Decl 'SEMICOLON'
Stmt -> Assign 'SEMICOLON'
Stmt -> IfStmt
Stmt -> WhileStmt
Stmt -> Block
Stmt -> PrintStmt 'SEMICOLON'
Decl -> Type 'ID'
Type -> 'INT'
Type -> 'FLOAT'
Assign -> 'ID' 'ASSIGN' Expr
IfStmt -> 'IF' 'LPAREN' BoolExpr 'RPAREN' Block 'ELSE' Block
IfStmt -> 'IF' 'LPAREN' BoolExpr 'RPAREN' Block
WhileStmt -> 'WHILE' 'LPAREN' BoolExpr 'RPAREN' Block
Block -> 'LBRACE' StmtList 'RBRACE'
PrintStmt -> 'PRINT' 'LPAREN' Expr 'RPAREN'
Expr -> Expr 'PLUS' Term
Expr -> Expr 'MINUS' Term
Expr -> Term
Term -> Term 'MUL' Factor
Term -> Term 'DIV' Factor
Term -> Term 'MOD' Factor
Term -> Factor
Factor -> 'ID'
Factor -> 'INT_LIT'
Factor -> 'FLOAT_LIT'
Factor -> 'LPAREN' Expr 'RPAREN'
BoolExpr -> BoolExpr 'OR' BoolAnd
BoolExpr -> BoolAnd
BoolAnd -> BoolAnd 'AND' BoolNot
BoolAnd -> BoolNot
BoolNot -> 'NOT' BoolNot
BoolNot -> RelExpr
BoolNot -> 'LPAREN' BoolExpr 'RPAREN'
RelExpr -> Expr 'LT' Expr
RelExpr -> Expr 'GT' Expr
RelExpr -> Expr 'LE' Expr
RelExpr -> Expr 'GE' Expr
RelExpr -> Expr 'EQ' Expr
RelExpr -> Expr 'NE' Expr
"""
# Create a CFG object from the grammar string
grammar = CFG.fromstring(grammar_string)
parser = EarleyChartParser(grammar)
def parse_sentence(tokens):
try:
return parser.parse(tokens)
except ValueError as e:
print(f"Syntax Error: {e}")
return []