Created
July 15, 2013 06:28
-
-
Save anonymous/5997860 to your computer and use it in GitHub Desktop.
formalize a string with nested tags, which give each tag.
'<1+<2+3>+4>+5'
after formalized:
'LEVEL1<1+LEVEL2<2+3LEVEL1>+4LEVEL1>+5'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
text = '<1+<2+3>+4>+5' | |
def formalize(text, ltag='<', rtag='>', token='LEVEL'): | |
pattern = r'({left})([^{left}{right}]*)|({right})([^{left}{right}]*)'.format(left=ltag, right=rtag) | |
print pattern | |
level = 0 | |
ret = [] | |
for match in re.finditer(pattern, text): | |
g0, g1, g2, g3, g4 = match.group(0, 1, 2, 3, 4) | |
if g1: | |
level += 1 | |
ret.append('{token}{level}{tag}{text}'.format(token=token,level=level, tag=g1, text=g2 or '')) | |
elif g3: | |
level =+ 1 | |
ret.append('{token}{level}{tag}{text}'.format(token=token, level=level, tag=g3, text= g4 or '')) | |
complete = True | |
if level != 0: | |
complete = False | |
return ''.join(ret), complete | |
print formalize(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment