Guest User

xkcd2holiday1.py

a guest
Jan 7th, 2014
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3. ''' Fetch details for a given xkcd comic number.
  4.    If no number is given, fetch the latest data.
  5.    
  6.    Then format into HTML suitable for the Holiday forum
  7.    http://tokyo3.org/forums/holiday/
  8.  
  9.    Added 2013.10.19
  10.    Escape HTML special chars <>&" as well as Textile formatting chars: !*+-@^_~ and []
  11.                                                                                                                                              
  12. '''                                                                                                                                            
  13.  
  14. import sys, re, urllib2, json
  15.  
  16. Base = 'http://xkcd.com/'  
  17. Tail = 'info.0.json'
  18.  
  19. months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
  20.     'July', 'August', 'September', 'October', 'November', 'December']
  21.    
  22. def bold(s): return '<b>%s</b>' % s
  23.  
  24. #Escape HTML and Textile special chars to numeric character references.
  25. pescape = re.compile(r'[!"&*+\-<>@[\]^_~]')
  26.  
  27. #def chrtoncr(c): return '&#%d;' % ord(c)
  28.    
  29. def matchobj_to_ncr(m):
  30.     return '&#%d;' % ord(m.group())
  31.    
  32. def escape(s):
  33.     return pescape.sub(matchobj_to_ncr, s)
  34.  
  35. def main():
  36.     n = len(sys.argv) > 1 and sys.argv[1] or ''
  37.     url = '%s%s/%s' % (Base, n, Tail)
  38.     print >>sys.stderr, url
  39.    
  40.     try:
  41.         f = urllib2.urlopen(url)
  42.         a = f.read()
  43.         f.close()
  44.     except urllib2.HTTPError, e:
  45.         print e
  46.         exit(1)
  47.  
  48.     #Load JSON string data into a dict
  49.     d = json.loads(a)
  50.    
  51.     num = d['num']
  52.     print bold('xkcd #%s' % num)
  53.     print 'published %s %s %s\n<br>' % (d['day'], months[int(d['month'])], d['year'])
  54.     print bold('%s\n' % escape(d['title']))
  55.    
  56.     print '<a href="http://xkcd.com/%s"><img src="%s" title="%s" style="background:white; padding:10px"></a>' % (num, d['img'], escape(d['alt']))
  57.    
  58.     trans = [i.replace('[[', '{').replace(']]', '}') for i in d['transcript'].splitlines() if not i.startswith('{{')]
  59.     if trans:
  60.         print '<br>\n%s\n%s' % (bold('Transcript'), escape('\n'.join(trans)))
  61.  
  62. if __name__ == '__main__':
  63.     main()
Advertisement
Add Comment
Please, Sign In to add comment