~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

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