Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python
- ''' Fetch details for a given xkcd comic number.
- If no number is given, fetch the latest data.
- Then format into HTML suitable for the Holiday forum
- http://tokyo3.org/forums/holiday/
- Added 2013.10.19
- Escape HTML special chars <>&" as well as Textile formatting chars: !*+-@^_~ and []
- '''
- import sys, re, urllib2, json
- Base = 'http://xkcd.com/'
- Tail = 'info.0.json'
- months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
- 'July', 'August', 'September', 'October', 'November', 'December']
- def bold(s): return '<b>%s</b>' % s
- #Escape HTML and Textile special chars to numeric character references.
- pescape = re.compile(r'[!"&*+\-<>@[\]^_~]')
- #def chrtoncr(c): return '&#%d;' % ord(c)
- def matchobj_to_ncr(m):
- return '&#%d;' % ord(m.group())
- def escape(s):
- return pescape.sub(matchobj_to_ncr, s)
- def main():
- n = len(sys.argv) > 1 and sys.argv[1] or ''
- url = '%s%s/%s' % (Base, n, Tail)
- print >>sys.stderr, url
- try:
- f = urllib2.urlopen(url)
- a = f.read()
- f.close()
- except urllib2.HTTPError, e:
- print e
- exit(1)
- #Load JSON string data into a dict
- d = json.loads(a)
- num = d['num']
- print bold('xkcd #%s' % num)
- print 'published %s %s %s\n<br>' % (d['day'], months[int(d['month'])], d['year'])
- print bold('%s\n' % escape(d['title']))
- print '<a href="http://xkcd.com/%s"><img src="%s" title="%s" style="background:white; padding:10px"></a>' % (num, d['img'], escape(d['alt']))
- trans = [i.replace('[[', '{').replace(']]', '}') for i in d['transcript'].splitlines() if not i.startswith('{{')]
- if trans:
- print '<br>\n%s\n%s' % (bold('Transcript'), escape('\n'.join(trans)))
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment