Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import re
- START = "> "
- BLOCKSEP_RE = re.compile("^ - ([a-zA-Z0-9\-_]+) -\s*$")
- class Post(object):
- def __init__(self, postid, fields=None):
- self.postid = postid
- if fields is None:
- self.fields = {}
- else:
- self.fields = fields
- def get(self, field):
- if field in self.fields:
- return self.fields[field]
- else:
- return None
- def __getattr__(self, field):
- if field in self.fields:
- return self.fields[field]
- else:
- raise AttributeError
- def parsePosts(posts):
- ret = []
- postbuf = []
- for line in posts.split("\n"):
- pass
- def parsePost(postid, postlines):
- ret = Post(postid)
- blockvar = None
- blockbuf = []
- blockmatch = None
- for line in postlines:
- line = line.rstrip()
- if not line:
- continue
- blockmatch = BLOCKSEP_RE.match(line)
- # handle the block delimiter, dump to var if necessary
- if blockmatch:
- # start block
- if blockvar is None:
- blockvar = blockmatch.group(1)
- continue
- # end block
- elif blockmatch.group(1) == blockvar:
- ret.fields[blockvar] = "\n".join(blockbuf)
- blockbuf = []
- blockvar = None
- continue
- if blockvar:
- blockbuf.append(line)
- else:
- try:
- key, val = line.split(" = ", 1)
- except ValueError as e:
- raise ValueError("invalid post line: \"{}\"".format(line)) from e
- ret.fields[key] = val
- if blockvar:
- raise SyntaxError("unclosed block: \"{}\"".format(blockvar))
- return ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement