86f6f1274fd7ccd97fa7900f352702b0ca8d79c7
[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 REGEXES = [
10     (r'<rdf:RDF[^>]*>(.|\n)*?</rdf:RDF>', ''),
11     (r'<motyw[^>]*>(.|\n)*?</motyw>', ''),
12     ('<(begin|end)\\sid=[\'|"][b|e]\\d+[\'|"]\\s/>', ''),
13     (r'<extra>((<!--<(elementy_poczatkowe|tekst_glowny)>-->)|(<!--</(elementy_poczatkowe|tekst_glowny)>-->))</extra>', ''),
14     (r'<uwaga>[^<]*</uwaga>', ''),
15     (r'<p[a|e|r|t]>(.|\n)*?</p>', ''),
16     (r'<[^>]+>', ''),
17     (r'/$', ''),
18     (r'---', u'—'),
19     (r'--', u'-'),
20     (r',,', u'„'),
21     (r'"', u'”'),
22 ]
23
24
25 if __name__ == '__main__':
26     # Parse commandline arguments
27     usage = """Usage: %prog [options] SOURCE [SOURCE...]
28     Convert SOURCE files to TXT format."""
29
30     parser = optparse.OptionParser(usage=usage)
31
32     parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
33         help='print status messages to stdout')
34
35     options, input_filenames = parser.parse_args()
36
37     if len(input_filenames) < 1:
38         parser.print_help()
39         exit(1)
40
41     # Do some real work
42     for input_filename in input_filenames:
43         if options.verbose:
44             print input_filename
45         
46         output_filename = os.path.splitext(input_filename)[0] + '.txt'
47         
48         xml = codecs.open(input_filename, 'r', encoding='utf-8').read()
49         for pattern, repl in REGEXES:
50             # print pattern, repl
51             xml, n = re.subn(pattern, repl, xml)
52             # print n
53             
54         output = codecs.open(output_filename, 'w', encoding='utf-8')
55         output.write(xml)
56