Created
December 31, 2008 11:03
-
-
Save sma/41947 to your computer and use it in GitHub Desktop.
example of parsing a yaml-like key-value data structure
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
# encoding: utf-8 | |
s = u""" | |
title: An example | |
author: Stefan | |
date: 2008-12-02 12:03:00 | |
text: | |
This is the blog entry and | |
a longer text which can have | |
paragraphs. | |
This text goes up to but not | |
including a "•" in a single | |
line. | |
• | |
keywords: foo, bar, baz | |
""" | |
import re | |
RE = re.compile(r"\s*(\w+):(?:\s+(.*)\s*)?$", re.U) | |
def parse(s): | |
attrs = {} | |
lines = iter(s.splitlines()) | |
for line in lines: | |
m = RE.match(line) | |
if m: | |
if m.group(2) is None: | |
value = [] | |
for line in lines: | |
if line == u"•": | |
break | |
value.append(line) | |
attrs[m.group(1)] = "\n".join(value) | |
else: | |
attrs[m.group(1)] = m.group(2) | |
return attrs | |
print parse(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment