Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ply.lex as lex
- import ply.yacc as yacc
- # List of token names. This is always required.
- tokens = (
- 'CLB',
- 'CRB',
- 'Colon',
- 'Comma',
- 'Number',
- 'String',
- 'True',
- 'False',
- 'Null',
- 'LSB',
- 'RSB'
- )
- # Regular expression rules for simple tokens
- t_CLB = r'\{'
- t_CRB = r'\}'
- t_Colon = r':'
- t_Comma = r','
- t_LSB = r'\['
- t_RSB = r'\]'
- def t_Number(t):
- r'(-?)(0|([1-9][0-9]*))((\.[0-9]*)?)(([eE]((\+|-)?)(([0-9])*))?)'
- return t
- def t_String(t):
- r'\"([^"\\\u0000-\u001F\u007F-\u009F]|(\\["/\\bfnrtu0000-uFFFF]))*\"'
- return t
- def t_True(t):
- r'true'
- t.value = True
- return t
- def t_False(t):
- r'false'
- t.value = False
- return t
- def t_Null(t):
- r'null'
- t.value = None
- return t
- def t_newline(t):
- r'\n+'
- lexer.lineno += len(t.value)
- # Error handling rule
- def t_error(t):
- print('Illegal character "%s"' % t.value[0])
- # String containing ignored characters (spaces and tabs)
- t_ignore = ' \t'
- # Build the lexer
- lexer = lex.lex()
- def p_Value(p):
- """
- Value : Number
- | String
- | True
- | Null
- | False
- | Object
- | Array """
- def p_Object(p):
- '''
- Object : CLB pairs CRB
- '''
- def p_pairs(p):
- '''
- pairs : pair
- |
- '''
- def p_pair(p):
- '''
- pair : String Colon Value Comma pair
- | String Colon Value
- '''
- def p_Array(p):
- '''
- Array : LSB Valuesf RSB
- '''
- def p_Values(p):
- '''
- Values : Value Comma Value
- | Value
- '''
- def p_Valuesf(p):
- '''
- Valuesf : Values
- |
- '''
- def p_error(p):
- print('Incorrect Syntax')
- yacc.yacc()
- data = '[1,2,3]'
- print(yacc.parse(data))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement