~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

Viewing changes to trunk/lib/corpusfg/plugins/replace-regex.py

  • Committer: tahoar
  • Date: 2012-05-02 15:46:23 UTC
  • Revision ID: svn-v4:bc069b21-dff4-4e29-a776-06a4e04bad4e::266
new layout. need to update code to use the new layout

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
# -*- coding: utf8 -*-
 
3
 
 
4
#===============================================================================
 
5
# Author: Walapa Muangjeen
 
6
#===============================================================================
 
7
 
 
8
#version:
 
9
#4.0.264 - version update
 
10
 
 
11
import os
 
12
import sys
 
13
import re
 
14
import common as cf
 
15
import logging
 
16
 
 
17
logger = logging.getLogger('.'.join([os.path.splitext(os.path.basename(sys.argv[0]))[0],'manager','filtergraph',__name__]))
 
18
skipclose = True
 
19
 
 
20
class filter(object):
 
21
 
 
22
        cfg = { 
 
23
                'encoding': 'utf8',
 
24
                'inputfile': '',
 
25
                'outputfile': '',
 
26
                'searchfor': '(.)',
 
27
                'replacewith': '\\1',
 
28
                'version': '4.0.264',
 
29
                }
 
30
        encoding = 'utf8'
 
31
        inputfile = ''
 
32
        outputfile = ''
 
33
        searchfor = '(.)'
 
34
        replacewith = '\\1'
 
35
        isopen = False
 
36
        p = object
 
37
        errors = []
 
38
 
 
39
        def open(self,parent,cfg):
 
40
                self.encoding = 'utf8' if 'utf8' in cfg['encoding'].lower().replace('-','') else cfg['encoding']
 
41
                self.inputfile = cfg['inputfile'].replace('%(rootfolder)s',self.p.rootfolder) if cfg['inputfile'] else self.inputfile
 
42
                self.outputfile = cfg['outputfile'].replace('%(rootfolder)s',self.p.rootfolder) if cfg['outputfile'] else self.outputfile
 
43
                if (self.inputfile and not self.outputfile) or (not self.inputfile and self.outputfile):
 
44
                        self.errors.append([__name__,'invalid','[%s] inputfile=%s without outputfile= value'%(__name__,cfg['inputfile'])])
 
45
                        logger.warn('%s\t%s',*self.errors[-1][1:])
 
46
 
 
47
                self.searchfor = cfg['searchfor'][1:-1] if cfg['searchfor'].startswith('\"') and cfg['searchfor'].endswith('\"') else cfg['searchfor']
 
48
                self.replacewith = cfg['replacewith'][1:-1] if cfg['replacewith'].startswith('\"') and cfg['replacewith'].endswith('\"') else cfg['replacewith']
 
49
                self.regex = re.compile((self.searchfor), re.I + re.U)
 
50
 
 
51
        def run(self,k):
 
52
                global skipclose
 
53
                skipclose = not self.inputfile
 
54
                if self.inputfile: return
 
55
 
 
56
                self.p.cfoutput[k]['tempbuff'] = [self.regex.sub(self.replacewith,line) for line in self.p.cfoutput[k]['tempbuff']]
 
57
 
 
58
        def flush(self,k):
 
59
                return
 
60
 
 
61
        def close(self):
 
62
                if skipclose: return
 
63
 
 
64
                import codecs
 
65
 
 
66
                if not os.path.exists(self.inputfile):
 
67
                        self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.inputfile)])
 
68
                        logger.error('%s\t%s',*self.errors[-1][1:])
 
69
                        return
 
70
 
 
71
                # make output folder
 
72
                try:
 
73
                        os.makedirs(os.path.dirname(self.outputfile))
 
74
                except OSError,e:
 
75
                        if not e.errno == 17:
 
76
                                logger.exception('%s\t%s, %s, %s',*['failed',e.errno,e.strerror,e.filename,])
 
77
                                raise OSError(e)
 
78
 
 
79
                # open input and output files
 
80
                out = self.outputfile
 
81
                if out == self.inputfile:
 
82
                        import tempfile
 
83
                        fd,out = tempfile.mkstemp(suffix='.tmp', prefix='~', dir=self.p.tempdir)
 
84
                        os.close(fd)
 
85
                try:
 
86
                        o = codecs.open(out,'w',self.encoding)
 
87
                        i = codecs.open(self.inputfile,'r',self.encoding)
 
88
                except:
 
89
                        raise RuntimeError('Failed to open [%s] input/output files'%(__name__))
 
90
 
 
91
                sys.stderr.write('[%s] %s\n   Please wait'%(__name__,self.outputfile))
 
92
                cnt = 0
 
93
                try:
 
94
                        # loop writes output line-by-line
 
95
                        for line in i:
 
96
                                o.write('%s\n'%(self.regex.sub(self.replacewith,line.rstrip('\r\n'))))
 
97
                                cnt += 1
 
98
                                if not cnt%5000: sys.stderr.write('.')
 
99
                        sys.stderr.write('\n')
 
100
                        # close input and output files
 
101
                        i.close()
 
102
                        o.close()
 
103
 
 
104
                        if not out == self.outputfile:
 
105
                                import shutil
 
106
                                shutil.move(out,self.outputfile)
 
107
 
 
108
                except KeyboardInterrupt:
 
109
                        os.unlink(out)
 
110
                        raise KeyboardInterrupt()
 
111
 
 
112
                if not os.path.exists(self.outputfile):
 
113
                        self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.outputfile)])
 
114
                        logger.error('%s\t%s',*self.errors[-1][1:])
 
115
 
 
116
def usage():
 
117
        '''Command prompt help.'''
 
118
        return "\n%s\n\tUsage:\n\tfrom %s import filter\n"%(
 
119
        os.path.basename(sys.argv[0]),
 
120
        os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
121
        )
 
122
 
 
123
licensetxt=u'''CorpusFiltergraph™ v4.0
 
124
Copyright © 2010-2012 Precision Translation Tools Co., Ltd.
 
125
 
 
126
This program is free software: you can redistribute it and/or modify
 
127
it under the terms of the GNU Lesser General Public License as published by
 
128
the Free Software Foundation, either version 3 of the License, or
 
129
(at your option) any later version.
 
130
 
 
131
This program is distributed in the hope that it will be useful,
 
132
but WITHOUT ANY WARRANTY; without even the implied warranty of
 
133
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
134
GNU Lesser General Public License for more details.
 
135
 
 
136
You should have received a copy of the GNU Lesser General Public License
 
137
along with this program.  If not, see http://www.gnu.org/licenses/.
 
138
 
 
139
For more information, please contact Precision Translation Tools Co., Ltd.
 
140
at: http://www.precisiontranslationtools.com'''
 
141
 
 
142
if __name__ == "__main__":
 
143
        import os
 
144
        import sys
 
145
        sys.stdout.write(usage().encode('utf8')+'\n')