Skip to content

Instantly share code, notes, and snippets.

@sbp
Created May 29, 2011 10:50
Show Gist options
  • Save sbp/997644 to your computer and use it in GitHub Desktop.
Save sbp/997644 to your computer and use it in GitHub Desktop.
Convert a lightweight text format to hypertext
#!/usr/bin/env python
import sys, re
with open(sys.argv[1], 'rb') as f:
text = unicode(f.read(), 'utf-8')
r_paragraph = re.compile(ur'^|(?<=\n\n)(?=\S)')
r_link = re.compile(ur'(?s)(?<!\\)\*([^*]+)\*(\W?)\s+(\S*[./]\S+)')
r_em = re.compile(ur'(?<!\\)\*([^*]+)\*')
def s_link(match):
a, b, c = match.groups()
if (not ':' in c) and (not c.startswith('.') or c.startswith('/')):
c = 'http://' + c
if a.startswith('[') and a.endswith(']'):
return '<img src="%s" alt="%s">%s' % (c, a[1:-1], b)
return '<a href="%s">%s</a>%s' % (c, a, b)
text = text.replace('<', '&lt;')
text = r_link.sub(s_link, text)
text = r_em.sub(r'<strong>\g<1></strong>', text)
text = r_paragraph.sub('<p>', text)
text = text.replace('\\*', '*')
print text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment