| 1 |
import re, enum |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
group_regex = re.compile(r'\?P<(.+?)>') |
| 6 |
|
| 7 |
|
| 8 |
class Segment: |
| 9 |
"""Segment of parsed text""" |
| 10 |
def __init__(self, text, token=None, match=None, **params): |
| 11 |
self.text = text |
| 12 |
self.params = params |
| 13 |
if token and match: |
| 14 |
self.update_text(token, match) |
| 15 |
self.update_params(token, match) |
| 16 |
|
| 17 |
def update_text(self, token, match): |
| 18 |
"""Update text from results of regex match""" |
| 19 |
if isinstance(self.text, MatchGroup): |
| 20 |
self.text = self.text.get_group_value(token, match) |
| 21 |
|
| 22 |
def update_params(self, token, match): |
| 23 |
"""Update dict of params from results of regex match""" |
| 24 |
for k, v in self.params.items(): |
| 25 |
if isinstance(v, MatchGroup): |
| 26 |
self.params[k] = v.get_group_value(token, match) |
| 27 |
|
| 28 |
|
| 29 |
class Token: |
| 30 |
"""Definition of token which should be parsed from text""" |
| 31 |
def __init__(self, name, pattern_start, pattern_end=None, text=None, skip=False, **params): |
| 32 |
self.name = name |
| 33 |
self.group_start = '{}_start'.format(self.name) |
| 34 |
self.group_end = '{}_end'.format(self.name) if pattern_end else None |
| 35 |
self.pattern_start = self.modify_pattern(pattern_start, self.group_start) |
| 36 |
self.pattern_end = self.modify_pattern(pattern_end, self.group_end) if pattern_end else None |
| 37 |
self.text = text |
| 38 |
self.skip = skip |
| 39 |
self.params = params |
| 40 |
|
| 41 |
def modify_pattern(self, pattern, group): |
| 42 |
"""Rename groups in regex pattern and enclose it in named group""" |
| 43 |
pattern = group_regex.sub(r'?P<{}_\1>'.format(self.name), pattern) |
| 44 |
return r'(?P<{}>{})'.format(group, pattern) |
| 45 |
|
| 46 |
|
| 47 |
class MatchGroup: |
| 48 |
"""Name of regex group which should be replaced by its value when token is parsed""" |
| 49 |
def __init__(self, group, func=None): |
| 50 |
self.group = group |
| 51 |
self.func = func |
| 52 |
|
| 53 |
def get_group_value(self, token, match): |
| 54 |
"""Return value of regex match for the specified group""" |
| 55 |
try: |
| 56 |
value = match.group('{}_{}'.format(token.name, self.group)) |
| 57 |
except IndexError: |
| 58 |
value = '' |
| 59 |
return self.func(value) if callable(self.func) else value |
| 60 |
|
| 61 |
|
| 62 |
class MatchType(enum.Enum): |
| 63 |
"""Type of token matched by regex""" |
| 64 |
start = 1 |
| 65 |
end = 2 |
| 66 |
single = 3 |
| 67 |
|
| 68 |
|
| 69 |
class Parser: |
| 70 |
"""Simple regex-based lexer/parser for inline markup""" |
| 71 |
def __init__(self, tokens): |
| 72 |
self.tokens = tokens |
| 73 |
self.regex = self.build_regex(tokens) |
| 74 |
self.groups = self.build_groups(tokens) |
| 75 |
|
| 76 |
def preprocess(self, text): |
| 77 |
"""Preprocess text before parsing (should be reimplemented by subclass)""" |
| 78 |
return text |
| 79 |
|
| 80 |
def postprocess(self, text): |
| 81 |
"""Postprocess text after parsing (should be reimplemented by subclass)""" |
| 82 |
return text |
| 83 |
|
| 84 |
def build_regex(self, tokens): |
| 85 |
"""Build compound regex from list of tokens""" |
| 86 |
patterns = [] |
| 87 |
for token in tokens: |
| 88 |
patterns.append(token.pattern_start) |
| 89 |
if token.pattern_end: |
| 90 |
patterns.append(token.pattern_end) |
| 91 |
return re.compile('|'.join(patterns), re.DOTALL) |
| 92 |
|
| 93 |
def build_groups(self, tokens): |
| 94 |
"""Build dict of groups from list of tokens""" |
| 95 |
groups = {} |
| 96 |
for token in tokens: |
| 97 |
match_type = MatchType.start if token.group_end else MatchType.single |
| 98 |
groups[token.group_start] = (token, match_type) |
| 99 |
if token.group_end: |
| 100 |
groups[token.group_end] = (token, MatchType.end) |
| 101 |
return groups |
| 102 |
|
| 103 |
def get_matched_token(self, match): |
| 104 |
"""Find which token has been matched by compound regex""" |
| 105 |
match_groupdict = match.groupdict() |
| 106 |
for group in self.groups: |
| 107 |
if match_groupdict[group] is not None: |
| 108 |
token, match_type = self.groups[group] |
| 109 |
return (token, match_type, group) |
| 110 |
|
| 111 |
def get_params(self, token_stack): |
| 112 |
"""Get params from stack of tokens""" |
| 113 |
params = {} |
| 114 |
for token in token_stack: |
| 115 |
params.update(token.params) |
| 116 |
return params |
| 117 |
|
| 118 |
def remove_token(self, token_stack, token): |
| 119 |
"""Remove last occurance of token from stack""" |
| 120 |
token_stack.reverse() |
| 121 |
try: |
| 122 |
token_stack.remove(token) |
| 123 |
retval = True |
| 124 |
except ValueError: |
| 125 |
retval = False |
| 126 |
token_stack.reverse() |
| 127 |
return retval |
| 128 |
|
| 129 |
def parse(self, text): |
| 130 |
"""Parse text to obtain list of Segments""" |
| 131 |
text = self.preprocess(text) |
| 132 |
token_stack = [] |
| 133 |
last_pos = 0 |
| 134 |
|
| 135 |
|
| 136 |
for match in self.regex.finditer(text): |
| 137 |
|
| 138 |
token, match_type, group = self.get_matched_token(match) |
| 139 |
|
| 140 |
|
| 141 |
params = self.get_params(token_stack) |
| 142 |
|
| 143 |
|
| 144 |
skip = token_stack[-1].skip if token_stack else False |
| 145 |
|
| 146 |
|
| 147 |
if match_type == MatchType.end: |
| 148 |
if not skip or token_stack[-1] == token: |
| 149 |
removed = self.remove_token(token_stack, token) |
| 150 |
if removed: |
| 151 |
skip = False |
| 152 |
else: |
| 153 |
skip = True |
| 154 |
|
| 155 |
if not skip: |
| 156 |
|
| 157 |
start_pos = match.start(group) |
| 158 |
if start_pos > last_pos: |
| 159 |
yield Segment(self.postprocess(text[last_pos:start_pos]), **params) |
| 160 |
|
| 161 |
|
| 162 |
if match_type == MatchType.start: |
| 163 |
token_stack.append(token) |
| 164 |
elif match_type == MatchType.single: |
| 165 |
single_params = params.copy() |
| 166 |
single_params.update(token.params) |
| 167 |
single_text = token.text if token.text is not None else match.group(group) |
| 168 |
yield Segment(single_text, token=token, match=match, **single_params) |
| 169 |
|
| 170 |
|
| 171 |
last_pos = match.end(group) |
| 172 |
|
| 173 |
|
| 174 |
if last_pos < len(text): |
| 175 |
params = self.get_params(token_stack) |
| 176 |
yield Segment(self.postprocess(text[last_pos:]), **params) |