Advertisement
hxrussia

Replace $...$ expressions to Latex formulae

Sep 11th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import re
  6. import sys
  7. import urllib
  8.  
  9. path = 'images/latex'
  10.  
  11. index = 0
  12. saved = {}
  13.  
  14. def save_formula(expr):
  15.     global index
  16.    
  17.     try:
  18.         return saved[expr]
  19.     except KeyError:
  20.         pass
  21.    
  22.     link = 'http://latex.codecogs.com/png.latex?' + urllib.quote(expr)
  23.     index += 1
  24.     filename = os.path.join(path, '%s.png' % index)
  25.     conn = urllib.urlopen(link)
  26.     with open(filename, 'wb') as f:
  27.         f.write(conn.read())
  28.     conn.close()
  29.    
  30.     saved[expr] = filename
  31.     sys.stderr.write('%s -> %s\n' % (expr, filename))
  32.     return filename
  33.  
  34. def main():
  35.     content = sys.stdin.read()
  36.     content = re.sub(r'(?s)\$(.*?)\$', lambda match: (
  37.         '<img src="%s" />' % save_formula(match.groups()[0].strip())
  38.     ), content)
  39.     sys.stdout.write(content)
  40.  
  41. if __name__ == '__main__':
  42.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement