Commits

Peter Ward committed aa410f2

add utils module

  • Participants
  • Parent commits 1e3dc4e

Comments (0)

Files changed (1)

shinypress/utils.py

+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
+
+import itertools
+
+def group_paragraphs(lines):
+    """
+    Group an iterable by groups of non-empty lines.
+
+    Warning: the iterables this returns must be used in order,
+    otherwise badness will ensue.
+    """
+
+    # number of the current paragraph
+    i = [0]
+    up_to = lambda j: i[0] == j
+    finished = lambda: up_to(-1)
+    def next_paragraph():
+        i[0] += 1
+    def finish():
+        i[0] = -1
+
+    def make_iter(j):
+        while True:
+            if finished():
+                break
+
+            if not up_to(j):
+                raise ValueError, "iterators must be used in order"
+
+            try:
+                line = lines.next()
+            except StopIteration:
+                finish()
+                return
+
+            if not line:
+                break
+
+            yield line
+
+        next_paragraph()
+
+    for j in itertools.count():
+        yield make_iter(j)
+        if finished():
+            break
+