assume unicode in flux, may change again based on disucssion wiht phasefx
[migration-tools.git] / text / html2tsv.py
1 #!/usr/bin/python
2 # -*- coding: iso-8859-1 -*-
3 # Hello, this program is written in Python - http://python.org
4 programname = 'html2tsv - version 2002-09-20 - http://sebsauvage.net'
5
6 import sys, getopt, os.path, glob, HTMLParser, re
7
8 try:    import psyco ; psyco.jit()  # If present, use psyco to accelerate the program
9 except: pass
10
11 def usage(progname):
12     ''' Display program usage. '''
13     progname = os.path.split(progname)[1]
14     if os.path.splitext(progname)[1] in ['.py','.pyc']: progname = 'python '+progname
15     return '''%s
16 A coarse HTML tables to TSV (Tab-Separated Values) converter.
17
18 Syntax    : %s source.html
19
20 Arguments : source.html is the HTML file you want to convert to TSV.
21             By default, the file will be converted to tsv with the same
22             name and the tsv extension (source.html -> source.tsv)
23             You can use * and ?.
24
25 Examples   : %s mypage.html
26            : %s *.html
27
28 This program is public domain.
29 Author : Sebastien SAUVAGE <sebsauvage at sebsauvage dot net>
30          http://sebsauvage.net
31 ''' % (programname, progname, progname, progname)
32
33 class html2tsv(HTMLParser.HTMLParser):
34     ''' A basic parser which converts HTML tables into TSV.
35         Feed HTML with feed(). Get TSV with getTSV(). (See example below.)
36         All tables in HTML will be converted to TSV (in the order they occur
37         in the HTML file).
38         You can process very large HTML files by feeding this class with chunks
39         of html while getting chunks of TSV by calling getTSV().
40         Should handle badly formated html (missing <tr>, </tr>, </td>,
41         extraneous </td>, </tr>...).
42         This parser uses HTMLParser from the HTMLParser module,
43         not HTMLParser from the htmllib module.
44         Example: parser = html2tsv()
45                  parser.feed( open('mypage.html','rb').read() )
46                  open('mytables.tsv','w+b').write( parser.getTSV() )
47         This class is public domain.
48         Author: Sébastien SAUVAGE <sebsauvage at sebsauvage dot net>
49                 http://sebsauvage.net
50         Versions:
51            2002-09-19 : - First version
52            2002-09-20 : - now uses HTMLParser.HTMLParser instead of htmllib.HTMLParser.
53                         - now parses command-line.
54         To do:
55             - handle <PRE> tags
56             - convert html entities (&name; and &#ref;) to Ascii.
57             '''
58     def __init__(self):
59         HTMLParser.HTMLParser.__init__(self)
60         self.TSV = ''      # The TSV data
61         self.TSVrow = ''   # The current TSV row beeing constructed from HTML
62         self.inTD = 0      # Used to track if we are inside or outside a <TD>...</TD> tag.
63         self.inTR = 0      # Used to track if we are inside or outside a <TR>...</TR> tag.
64         self.re_multiplespaces = re.compile('\s+')  # regular expression used to remove spaces in excess
65         self.rowCount = 0  # TSV output line counter.
66     def handle_starttag(self, tag, attrs):
67         if   tag == 'tr': self.start_tr()
68         elif tag == 'td': self.start_td()
69     def handle_endtag(self, tag):
70         if   tag == 'tr': self.end_tr()
71         elif tag == 'td': self.end_td()         
72     def start_tr(self):
73         if self.inTR: self.end_tr()  # <TR> implies </TR>
74         self.inTR = 1
75     def end_tr(self):
76         if self.inTD: self.end_td()  # </TR> implies </TD>
77         self.inTR = 0            
78         if len(self.TSVrow) > 0:
79             self.TSV += self.TSVrow[:-1]
80             self.TSVrow = ''
81         self.TSV += '\n'
82         self.rowCount += 1
83     def start_td(self):
84         if not self.inTR: self.start_tr() # <TD> implies <TR>
85         self.TSVrow += ''
86         self.inTD = 1
87     def end_td(self):
88         if self.inTD:
89             self.TSVrow += '\t'  
90             self.inTD = 0
91     def handle_data(self, data):
92         if self.inTD:
93             self.TSVrow += self.re_multiplespaces.sub(' ',data.replace('\t',' ').replace('\n','').replace('\r','').replace('"','""'))
94     def getTSV(self,purge=False):
95         ''' Get output TSV.
96             If purge is true, getTSV() will return all remaining data,
97             even if <td> or <tr> are not properly closed.
98             (You would typically call getTSV with purge=True when you do not have
99             any more HTML to feed and you suspect dirty HTML (unclosed tags). '''
100         if purge and self.inTR: self.end_tr()  # This will also end_td and append last TSV row to output TSV.
101         dataout = self.TSV[:]
102         self.TSV = ''
103         return dataout
104
105
106 if __name__ == "__main__":
107     try: # Put getopt in place for future usage.
108         opts, args = getopt.getopt(sys.argv[1:],None)
109     except getopt.GetoptError:
110         print usage(sys.argv[0])  # print help information and exit:
111         sys.exit(2)
112     if len(args) == 0:
113         print usage(sys.argv[0])  # print help information and exit:
114         sys.exit(2)       
115     print programname
116     html_files = glob.glob(args[0])
117     for htmlfilename in html_files:
118         outputfilename = os.path.splitext(htmlfilename)[0]+'.tsv'
119         parser = html2tsv()
120         print 'Reading %s, writing %s...' % (htmlfilename, outputfilename)
121         try:
122             htmlfile = open(htmlfilename, 'rb')
123             tsvfile = open( outputfilename, 'w+b')
124             data = htmlfile.read(8192)
125             while data:
126                 parser.feed( data )
127                 tsvfile.write( parser.getTSV() )
128                 sys.stdout.write('%d TSV rows written.\r' % parser.rowCount)
129                 data = htmlfile.read(8192)
130             tsvfile.write( parser.getTSV(True) )
131             tsvfile.close()
132             htmlfile.close()
133         except:
134             print 'Error converting %s        ' % htmlfilename
135             try:    htmlfile.close()
136             except: pass
137             try:    tsvfile.close()
138             except: pass
139     print 'All done.                                      '