Extracted fragment extraction in bookfragments to extract_fragments function. Put...
[wolnelektury.git] / bin / book2html.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import cStringIO
4 import re
5 import optparse
6 import os
7 import sys
8
9 from lxml import etree
10
11
12 def transform(input_filename, output_filename):
13     """Transforms file input_filename in XML to output_filename in XHTML."""
14     # Parse XSLT
15     style = etree.parse('book2html.xslt')
16
17     doc_file = cStringIO.StringIO()
18     expr = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
19
20     f = open(input_filename, 'r')
21     for line in f:
22         line = line.decode('utf-8')
23         line = expr.sub(u'<br/>\n', line).replace(u'---', u'—').replace(u',,', u'„')
24         doc_file.write(line.encode('utf-8'))
25     f.close()
26
27     doc_file.seek(0);
28
29     parser = etree.XMLParser(remove_blank_text=True)
30     doc = etree.parse(doc_file, parser)
31
32     result = doc.xslt(style)
33     result.write(output_filename, xml_declaration=True, pretty_print=True, encoding='utf-8')
34
35
36 if __name__ == '__main__':
37     # Parse commandline arguments
38     usage = """Usage: %prog [options] SOURCE [SOURCE...]
39     Convert SOURCE files to HTML format."""
40
41     parser = optparse.OptionParser(usage=usage)
42
43     parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
44         help='print status messages to stdout')
45
46     options, input_filenames = parser.parse_args()
47
48     if len(input_filenames) < 1:
49         parser.print_help()
50         exit(1)
51
52     # Do some real work
53     for input_filename in input_filenames:
54         if options.verbose:
55             print input_filename
56         
57         output_filename = os.path.splitext(input_filename)[0] + '.html'
58         transform(input_filename, output_filename)
59