~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

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