Created
January 3, 2009 11:48
-
-
Save sma/42828 to your computer and use it in GitHub Desktop.
example of parsing indented text using an indents stack
This file contains hidden or 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
# example of parsing indented text using an indents stack | |
def parse(lines): | |
output = [] | |
indents = [] | |
def set_indent(i, begin, end): | |
indents.append((i, end)) | |
output.append(begin) | |
def need_indent(indent): | |
while indent < indents[-1][0]: | |
output.append(indents.pop()[1]) | |
return indent > indents[-1][0] | |
set_indent(0, "<body>", "</body>") | |
for line in lines.splitlines(): | |
if line.strip(): | |
indent = len(line) - len(line.lstrip()); line = line[indent:] | |
if need_indent(indent): | |
if line.startswith("* "): | |
set_indent(indent, "<ul>", "</ul>") | |
else: | |
set_indent(indent, "<div class='indent'>", "</div>") | |
if line.startswith("* "): | |
set_indent(indent + 2, "<li>", "</li>") | |
line = line[2:] | |
output.append(line) | |
while indents: | |
output.append(indents.pop()[1]) | |
return "\n".join(output) | |
print parse(""" | |
Line. | |
Indented Line. | |
* List1 | |
* Sublist 1 | |
* Sublist 2 | |
* List2 | |
Line in List | |
Indented Line. | |
""") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment