home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / linux / utilities-general / convert.py < prev    next >
Text File  |  2006-05-04  |  5KB  |  150 lines

  1. #!/usr/bin/env python
  2. # Massages text into lightweight html, needs python 2 (probably 2.2).
  3. # Usage:
  4. # Edit OUT_PAT according to where you wnat the html files created, create
  5. # any directories needed and:
  6. # convert.py <textfile> [... <textfile>]
  7. # Paul Sorenson
  8. # $Revision$
  9. # vi: et
  10.  
  11. import sys
  12. import cgi  # only used for escaping html reserved characters in input text
  13. import re
  14.  
  15. class Converter:
  16.  
  17.     RE_URL = re.compile('''(http|ftp|https)://\S+''', re.IGNORECASE)
  18.     RE_ADDR = re.compile('''(<)?(\S+@[^&\s]+)(>)?''', re.IGNORECASE)
  19.     RE_FILE = re.compile('''^(.*?).?([^\.]*)$''')     # crack filenames
  20.     # Patterns used to select output filename (not thoroughly tested)
  21.     # %b gets base part of filename (everything up to last '.' if one exists, 
  22.     # otherwise everything), same as \g<1>
  23.     # %e gets extension (not including '.' if it exists) same as \g<2>
  24.     # If None then use stdout
  25.     OUT_PAT = None                     # everthing goes to stdout
  26.     #OUT_PAT = '''%b.%e.foo'''          # index.txt > index.txt.foo
  27.     #OUT_PAT = '''otherdir/%b.html'''   # index.txt > otherdir/index.html
  28.     #OUT_PAT = '''%b.html'''             # index.txt > index.html
  29.     #OUT_PAT = '''tmp/%b.html'''         # index.txt > tmp/index.html
  30.  
  31.     def __init__(self):
  32.         # Convert the user pattern to a valid replacement string
  33.         # There is nothing stopping the user enter \g<n> syntax directly
  34.         if self.OUT_PAT:
  35.             self.OUT_SUB = self.OUT_PAT.replace('%b', '''\g<1>''').replace('%e', '''\g<2>''')
  36.         self.index = {}
  37.         self.fileIndex = {}
  38.  
  39.     def convert(self, filename):
  40.         self.filename = filename
  41.         self.setOut(filename)
  42.         self.IN_PARA = 0
  43.         f = file(filename)
  44.         self.writeHeader()
  45.         for line in f.xreadlines():
  46.             self.lineproc(line)
  47.         if self.IN_PARA:
  48.             self.write('<p>\n')
  49.         self.writeFooter()
  50.         if self.OUT != sys.stdout:
  51.             self.OUT.close()
  52.  
  53.     def lineproc(self, line):
  54.         line = line.strip()
  55.         if len(line) == 0 and self.IN_PARA:
  56.             self.write('</p>\n')
  57.             self.IN_PARA = 0
  58.         else:   # we have some text
  59.             if not self.IN_PARA:
  60.                 self.write('<p>')
  61.                 self.IN_PARA = 1
  62.             else:
  63.                 self.write('<br>\n')
  64.             # Escape reserved HTML characters
  65.             line = cgi.escape(line, 1)
  66.             line = self.replaceEmailAddr(line)
  67.             line = self.replaceUrl(line)
  68.             self.write(line)
  69.  
  70.     def replaceUrl(self, line):
  71.         line = self.RE_URL.sub('''<a href="\g<0>">\g<0></a>''', line)
  72.         return line
  73.         
  74.     def replaceEmailAddr(self, line):
  75.         # In real life you might want to obfuscate email addresses.
  76.         line = self.RE_ADDR.sub('''<a href="mailto:\g<2>">\g<2></a>''', line)
  77.         return line
  78.  
  79.     def writeHeader(self):
  80.         self.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n\n')
  81.         self.write('<html><head><title>%s</title><link rel=stylesheet type="text/css" href="http://linuxmafia.com/redrick.css"></head><body><div id="content">\n' % self.filename)
  82.  
  83.     def writeFooter(self):
  84.         self.write('</div></body></html>\n')
  85.  
  86.     def setOut(self, filename):
  87.         if not self.OUT_PAT:
  88.             self.OUT = sys.stdout
  89.         else:
  90.             outFile = self.RE_FILE.sub(self.OUT_SUB, filename)
  91.             self.addIndex(filename, outFile)
  92.             print '<!-- ', filename, '-', outFile, '-->'
  93.             self.OUT = file(outFile, 'w')
  94.             #self.OUT = sys.stdout
  95.  
  96.     def addIndex(self, inFilename, outFilename):
  97.         base = self.RE_FILE.sub('''\g<1>''', inFilename)
  98.         ind = base.split('-')
  99.         map = self.index
  100.         for heading in ind:
  101.             if map.has_key(heading):
  102.                 map = map[heading]
  103.             else:
  104.                 map[heading] = {}
  105.                 map = map[heading]
  106.         self.fileIndex[''.join(ind)] = outFilename
  107.  
  108.     def writeIndex(self):
  109.         self.filename = 'index_auto.html'
  110.         self.OUT = file(self.filename, 'w')
  111.         self.writeHeader()
  112.         self.printMap(self.index, 0, '')
  113.         self.writeFooter()
  114.         self.OUT.close()
  115.  
  116.     def printMap(self, map, pad, lookup):
  117.         keys = map.keys()
  118.         keys.sort()
  119.         self.write('<ul>\n')
  120.         for key in keys:
  121.             filemap = lookup + key
  122.             if self.fileIndex.has_key(filemap):
  123.                 s = self.makeUrl(self.fileIndex[filemap], key)
  124.             else:
  125.                 s = key
  126.             self.write('<li>' + s + '\n') 
  127.             if map[key]:
  128.                 self.printMap(map[key], pad + 2, filemap)
  129.         self.write('</ul>\n')
  130.  
  131.     def makeUrl(self, ref, text):
  132.         val = None
  133.         if ref and text:
  134.             val = (ref, text)
  135.         else:
  136.             val = (ref, ref)
  137.         return '''<a href="%s">%s</a>''' % val
  138.  
  139.     def write(self, text):
  140.         self.OUT.write(text)
  141.  
  142.  
  143. def main():
  144.     c = Converter()
  145.     for arg in sys.argv[1:]:
  146.         c.convert(arg)
  147.     c.writeIndex()
  148.  
  149. main()
  150.