translations
[iramuteq] / import_txm.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2013 Pierre Ratinaud
5 #License: GNU/GPL
6
7
8 import os
9 import xml.sax
10 import glob
11
12 class TXMParser(xml.sax.ContentHandler) :
13     def __init__(self, fileout, encodage_out) :
14         self.fileout = fileout
15         self.encodage_out = encodage_out
16         self.sent = []
17
18     def startElement(self, name, attrs) :
19         self.name = name
20         if name == 'title' :
21             pass
22         if name == 's' :
23             pass
24         if name == 'taxonomy' :
25             pass
26         if name == 'text' :
27             self.text2stars(attrs)
28         if name == 'w' :
29             pass
30
31     def endElement(self, name) :
32         if name == 's' or name == 'w' :
33             self.printsent()
34         if name == 'p' :
35             self.printsent()
36             self.fileout.write('\n')
37           
38     def characters(self, content) :
39         if self.name == 'txm:form' :
40             if content not in [u'', u' ', u'\n', '\r'] :
41                 self.sent.append(content.rstrip('\n\r'))
42             #self.fileout.write(content.encode('utf8'))
43
44     def text2stars(self, attrs) :
45         stars = ['_'.join(val).replace(' ', '_').replace("'", '_').replace('/','').replace('.','').replace(';', '').replace(':', '').replace(u'ยท','') for val in attrs.items()]
46         stars = [''.join([u'*', val]) for val in stars]
47         stars = u'**** ' + ' '.join(stars)
48         self.fileout.write(stars.encode(self.encodage_out))
49         self.fileout.write('\n')
50
51     def printsent(self) :
52         if self.sent != [] :
53             sent = ' ' + ' '.join(self.sent)
54             for val in [u' .', u' ,', u' ;', u' :', u' ?', u' !', u' -'] :
55                 sent = sent.replace(val, val.strip())
56             sent = sent.replace("' ", "'")
57             self.fileout.write(sent.encode(self.encodage_out))
58         self.sent = []
59
60 def TXM2IRA(pathin, fileout, encodage_in, encodage_out) :
61         parser = xml.sax.make_parser()
62         files = glob.glob(os.path.join(pathin,'*.xml'))
63         if len(files) == 0 :
64             return 'nofile'
65         with open(fileout, 'w') as fout :
66             parser.setContentHandler(TXMParser(fout, encodage_out))
67             for f in files :
68                 parser.parse(open(f, 'r'))
69                 fout.write('\n\n')
70         return None