Read html_file in one go in book_text.html template. It fixes problems on WebFaction.
[wolnelektury.git] / lib / librarian / bin / book2txt.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import re
4 import os
5 import optparse
6 import codecs
7
8
9 HEADER = u"""
10 -----
11 Publikacja zrealizowana w ramach projektu Wolne Lektury (http://wolnelektury.pl/). Reprodukcja cyfrowa wykonana przez Bibliotekę Narodową z egzemplarza pochodzącego ze zbiorów BN.
12 Ten utwór nie jest chroniony prawem autorskim i znajduje się w domenie publicznej, co oznacza, że możesz go swobodnie wykorzystywać, publikować i rozpowszechniać.
13 Źródło:
14 -----
15
16 AUTOR: 
17 TYTUŁ: 
18 """
19
20
21 REGEXES = [
22     (r'<rdf:RDF[^>]*>(.|\n)*?</rdf:RDF>', ''),
23     (r'<motyw[^>]*>(.|\n)*?</motyw>', ''),
24     ('<(begin|end)\\sid=[\'|"][b|e]\\d+[\'|"]\\s/>', ''),
25     (r'<extra>((<!--<(elementy_poczatkowe|tekst_glowny)>-->)|(<!--</(elementy_poczatkowe|tekst_glowny)>-->))</extra>', ''),
26     (r'<uwaga>(.|\n)*?</uwaga>', ''),
27     (r'<p[a|e|r|t]>(.|\n)*?</p[a|e|r|t]>', ''),
28     (r'<[^>]+>', ''),
29     (r'/\n', '\n'),
30     (r'---', u'—'),
31     (r'--', u'-'),
32     (r',,', u'„'),
33     (r'"', u'”'),
34 ]
35
36
37 if __name__ == '__main__':
38     # Parse commandline arguments
39     usage = """Usage: %prog [options] SOURCE [SOURCE...]
40     Convert SOURCE files to TXT format."""
41
42     parser = optparse.OptionParser(usage=usage)
43
44     parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
45         help='print status messages to stdout')
46
47     options, input_filenames = parser.parse_args()
48
49     if len(input_filenames) < 1:
50         parser.print_help()
51         exit(1)
52
53     # Do some real work
54     for input_filename in input_filenames:
55         if options.verbose:
56             print input_filename
57         
58         output_filename = os.path.splitext(input_filename)[0] + '.txt'
59         
60         xml = codecs.open(input_filename, 'r', encoding='utf-8').read()
61         for pattern, repl in REGEXES:
62             # print pattern, repl
63             xml, n = re.subn(pattern, repl, xml)
64             # print n
65         
66         output = codecs.open(output_filename, 'w', encoding='utf-8')
67         output.write(HEADER)
68         output.write(xml)
69