import json import re import sys token_patterns = [ (r'#[^\n]*', None), (r'\s+', None),…
- User
import json import re import sys
token_patterns = [ (r'#[^\n]', None),
(r'\s+', None), (r'[', 'LBRACKET'), (r']', 'RBRACKET'), (r'{', 'LBRACE'), (r'}', 'RBRACE'), (r'%{', 'LMAPBRACE'), (r'=>', 'ARROW'), (r',', 'COMMA'), (r'(true|false)', 'BOOLEAN'), (r'(0|[1-9][0-9_])', 'INTEGER'),
(r':[A-Za-z_]\w*', 'ATOM'),
(r'[A-Za-z_]\w*', 'KEY'),
]regex_parts = [f'(?P<{name}>{pattern})' if name else f'(?:{pattern})' for pattern, name in token_patterns] token_regex = '|'.join(regex_parts) token_re = re.compile(token_regex)
class TokenizerException(Exception): pass
class ParserException(Exception): pass
def tokenize(text): pos = 0 while pos < len(text): match = token_re.match(text, pos) if not match: raise TokenizerException(f'Illegal character {text[pos]!r} at index {pos}') pos = match.end() if match.lastgroup:
yield match.lastgroup, match.group(match.lastgroup)class Node: def init(self, kind, value): self.kind = kind self.value = value
codedef to_json(self): if self.kind == "map": return {"%k": self.kind, "%v": {k.to_json()["%v"]: v.to_json() for k, v in self.value}} elif self.kind == "list": return {"%k": self.kind, "%v": [item.to_json() for item in self.value]} else: return {"%k": self.kind, "%v": self.value}class Parser: def init(self, tokens): self.tokens = iter(tokens) self.current_token = None self.next_token()
code - Assistant
It seems like your program is expecting input from
sys.stdin, but when you run the script, you're giving it an inline string"empty-lists"instead of actual data fromstdin.The error message you are receiving tells you that there's an "illegal character" at the beginning of the input, which is the '[' character. It's possible that the error results from improperly escaped regex patterns in your
token_patternslist.Looking carefully at the
token_patterns, there is a mistake with the regex pattern for detecting the left square bracket (): - User
there isnt any change in the regrex pattern u have written it as it as. fix the error correctly
- Assistant
Apologies for any confusion. The error in the regex patterns is indeed caused by the unescaped square brackets. In regular expressions, if you want to match literal square brackets, you have to escape them because they have special meaning in regex (they define character classes).
Here is the corrected version of the regex pattern:
python(r'\[', 'LBRACKET'), (r'\]', 'RBRACKET'),Now, applying this correction to your
token_patternslist should look like this:python