Skip to content

Instantly share code, notes, and snippets.

@anastasop
Created August 4, 2013 14:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anastasop/6150569 to your computer and use it in GitHub Desktop.
Save anastasop/6150569 to your computer and use it in GitHub Desktop.
Transform an outline file in opml format to a nice html for viewing
#!/usr/bin/python
from __future__ import print_function
import sys, xml.parsers.expat, sys
import pystache
if len(sys.argv) != 3:
print('usage: convopml.py <opml file> <html file>', file = sys.stderr)
sys.exit(2)
level = 0
urls = []
def startElement(name, attrs):
global level, urls, title
if name == 'outline':
level = level + 1
if 'htmlUrl' in attrs:
urls.append({'level': level, 'text': attrs['text'], 'url': attrs['htmlUrl']})
else:
urls.append({'level': level, 'text': attrs['text'], 'url': ''})
def endElement(name):
global level, urls
if name == 'outline':
level = level - 1
p = xml.parsers.expat.ParserCreate('UTF-8')
p.StartElementHandler = startElement
p.EndElementHandler = endElement
with open(sys.argv[1], 'rb') as f:
p.ParseFile(f)
tmpl = u"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Outline</title>
<style type="text/css">
.level1 { margin-left: 0em; margin-top: 1em; }
.level2 { margin-left: 4em; }
.level3 { margin-left: 8em; }
.level4 { margin-left: 12em; }
.level5 { margin-left: 16em; }
.level6 { margin-left: 20em; }
.level7 { margin-left: 24em; }
.level8 { margin-left: 28em; }
</style>
</head>
<body>
{{#urls}}
<div class="level{{level}}"><a href="{{url}}">{{text}}</a></div>
{{/urls}}
</body>
</html>
"""
t = pystache.render(tmpl, { 'urls': urls })
with open(sys.argv[2], 'wb') as f:
f.write(t.encode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment