Advertisement
ijontichy

postparse.py

May 22nd, 2012
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import re
  4.  
  5. START = "> "
  6.  
  7. BLOCKSEP_RE = re.compile("^ - ([a-zA-Z0-9\-_]+) -\s*$")
  8.  
  9. class Post(object):
  10.     def __init__(self, postid, fields=None):
  11.         self.postid = postid
  12.  
  13.         if fields is None:
  14.             self.fields = {}
  15.         else:
  16.             self.fields = fields
  17.  
  18.     def get(self, field):
  19.         if field in self.fields:
  20.             return self.fields[field]
  21.         else:
  22.             return None
  23.  
  24.     def __getattr__(self, field):
  25.         if field in self.fields:
  26.             return self.fields[field]
  27.         else:
  28.             raise AttributeError
  29.  
  30.  
  31. def parsePosts(posts):
  32.     ret = []
  33.     postbuf = []
  34.  
  35.     for line in posts.split("\n"):
  36.         pass
  37.  
  38.  
  39. def parsePost(postid, postlines):
  40.     ret = Post(postid)
  41.  
  42.     blockvar = None
  43.     blockbuf = []
  44.     blockmatch = None
  45.  
  46.     for line in postlines:
  47.         line = line.rstrip()
  48.  
  49.         if not line:
  50.             continue
  51.  
  52.         blockmatch = BLOCKSEP_RE.match(line)
  53.  
  54.         # handle the block delimiter, dump to var if necessary
  55.         if blockmatch:
  56.             # start block
  57.             if blockvar is None:
  58.                 blockvar = blockmatch.group(1)
  59.                 continue
  60.  
  61.             # end block
  62.             elif blockmatch.group(1) == blockvar:
  63.                 ret.fields[blockvar] = "\n".join(blockbuf)
  64.                 blockbuf = []
  65.                 blockvar = None
  66.                 continue
  67.  
  68.         if blockvar:
  69.             blockbuf.append(line)
  70.  
  71.         else:
  72.             try:
  73.                 key, val = line.split(" = ", 1)
  74.             except ValueError as e:
  75.                 raise ValueError("invalid post line: \"{}\"".format(line)) from e
  76.  
  77.             ret.fields[key] = val
  78.  
  79.     if blockvar:
  80.         raise SyntaxError("unclosed block: \"{}\"".format(blockvar))
  81.                          
  82.  
  83.     return ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement