Skip to content

Instantly share code, notes, and snippets.

@reusee
Created November 20, 2014 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reusee/93bc025719ec4ed8fbb9 to your computer and use it in GitHub Desktop.
Save reusee/93bc025719ec4ed8fbb9 to your computer and use it in GitHub Desktop.
markdown fix
src = '''\
Chapter 1
foo
- figure 1.1
bar
Section 1.1
- figure 1.2
- figure 1.3
baz
Section 1.2
- figure 1.4
Subsection 1.2.1
- figure 1.5
- figure 1.6
Chapter 2
- figure 2.1
Section 2.1
foo
Subsection 2.1.1
- figure 2.2
- figure 2.3
Subsection 2.1.2
- figure 2.4
Section 2.2
- figure 2.5
foobar
'''
import re
token_pattern = re.compile(r'''
(?P<name>Chapter|Section|Subsection|-\ figure)
\ (?P<num>([0-9]\.?)+)
''', re.VERBOSE)
def iterate(src, token_cb, text_cb):
pos = 0
while True:
token = token_pattern.search(src, pos)
if token is None: break
text_cb(src[pos:token.start()])
nums = [int(s) for s in token.group('num').split('.')]
token_cb(token.group('name'), nums)
pos = token.end()
text_cb(src[pos:len(src)])
def fix(src):
out = ''
def token_cb(name, nums):
nonlocal out
if nums[0] >= 2: nums[0] += 1
out += '%s %s' % (name, '.'.join(str(n) for n in nums))
def text_cb(text):
nonlocal out
out += text
iterate(src, token_cb, text_cb)
return out
print(fix(src))
'''output:
Chapter 1
foo
- figure 1.1
bar
Section 1.1
- figure 1.2
- figure 1.3
baz
Section 1.2
- figure 1.4
Subsection 1.2.1
- figure 1.5
- figure 1.6
Chapter 3
- figure 3.1
Section 3.1
foo
Subsection 3.1.1
- figure 3.2
- figure 3.3
Subsection 3.1.2
- figure 3.4
Section 3.2
- figure 3.5
foobar
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment