font size...
[iramuteq] / parse_europress.py
1 # -*- coding: utf-8 -*-
2 #Author: Pierre Ratinaud
3 #Copyright (c) 2014 Pierre Ratinaud
4 #License: GNU/GPL
5
6
7 #from BeautifulSoup import BeautifulSoup
8 import codecs
9 import os
10 from HTMLParser import HTMLParser
11
12
13 mois = {u'janvier' : '01',
14         u'février' : '02',
15         u'mars' : '03',
16         u'avril' : '04',
17         u'mai' : '05',
18         u'juin' : '06',
19         u'juillet' : '07',
20         u'août' : '08',
21         u'septembre' : '09',
22         u'octobre' : '10',
23         u'novembre' : '11',
24         u'décembre' : '12',
25         u'january' : '01',
26         u'february': '02',
27         u'march' : '03',
28         u'april': '04',
29         u'may': '05',
30         u'june' : '06',
31         u'july': '07',
32         u'august': '08',
33         u'september' : '09',
34         u'october': '10',
35         u'november': '11',
36         u'december': '12'}
37
38
39 def finddate(data):
40     data = data.split()
41     try :
42         day = int(data[0])
43         year = int(data[2])
44         month = mois[data[1]]
45     except :
46         return None
47     else :
48         return [`year`, month, '%02d' % day]
49
50 def makedate(date):
51     year = date[0:4]
52     month = date[4:6]
53     day = date[6:]
54     return [year, month, day]
55
56
57 # create a subclass and override the handler methods
58 class MyHTMLParser(HTMLParser):
59     def handle_starttag(self, tag, attrs):
60         #print "Encountered a start tag:", tag
61         if tag == 'span' :
62             if len(attrs) > 0 :
63                 if attrs[0][1] == 'DocPublicationName' :
64                     #print 'DocPublicationName'
65                     self.headercount = 0
66                     self.currentattr = 'DocPublicationName'
67                 elif attrs[0][1] == 'DocHeader' :
68                     self.headercount += 1
69                     self.currentattr = 'DocHeader'
70                 elif attrs[0][1] in ['TitreArticleVisu', 'titreArticleVisu', 'titreArticle'] :
71                     self.outfile.write('\n\n')
72                     self.meta.append('\n')
73                     self.outfile.write(' '.join(self.meta).encode('utf8', errors='replace'))
74                     self.meta = [u'****']
75                     self.nb += 1
76                     self.currentattr = 'TitreArticleVisu'
77                 elif attrs[0][1] == 'PubliC_lblNodoc' :
78                     self.currentattr = 'PubliC_lblNodoc'
79         elif tag == 'table' :
80             self.currentattr = None
81         elif tag == 'div' :
82             if len(attrs)>0 :
83                 if attrs[0][1] == 'publiC-lblNodoc' :
84                     self.currentattr = 'PubliC_lblNodoc'
85                 elif attrs[0][1] == 'DocText' :
86                     self.currentattr = 'TitreArticleVisu'
87                 elif attrs[0][1] == 'titreArticle' :
88                     self.currentattr = 'TitreArticleVisu'
89         elif tag == 'p' :
90             if len(attrs) > 0 :
91                 if attrs[0][1] == 'titreArticleVisu' :
92         #            self.outfile.write('\n\n')
93         #            self.meta.append('\n')
94         #            self.outfile.write(' '.join(self.meta).encode('utf8', errors='replace'))
95         #            self.meta = [u'****']
96         #            self.nb += 1
97                     self.currentattr = 'TitreArticleVisu'
98
99     def handle_endtag(self, tag):
100         pass
101         #print "Encountered an end tag :", tag
102     def handle_data(self, data):
103         #print self.currentattr
104         if self.currentattr == 'DocPublicationName' :
105             #print data
106             PublicationName = data.strip().replace(' ', '_').replace('(','').replace(')','').replace('-','').replace('.','').replace('/','').replace("'",'').replace(';', '').replace(':', '').replace(u'·','').lower()
107             PublicationName = PublicationName.split(',')[0]
108             if len([val for val in self.meta if val.startswith(u'*source_')]) == 0 :
109                 self.meta.append(u'*source_' + PublicationName)
110             self.currentattr = None
111 #        elif self.currentattr == 'DocHeader' :
112 #            date = finddate(data)
113 #            if date is not None :
114 #                self.meta += [u'*date_' + '-'.join(date), u'*am_' + '-'.join(date[0:2]), u'*annee_' + date[0]]
115         elif self.currentattr == 'TitreArticleVisu' :
116             #print data
117             if data.startswith(u'©') :
118                 self.currentattr = None
119                 return
120             self.content.append(' '.join(data.replace('\n', ' ').split()) + ' ')
121             #self.outfile.write(' '.join(data.replace('\n', ' ').split()).encode('utf8', errors='replace') + ' ')
122         elif self.currentattr == 'PubliC_lblNodoc' :
123             date = data.split(u'·')[1]#data[5:13]
124             date = makedate(date)
125             self.meta += [u'*date_' + '-'.join(date), u'*am_' + '-'.join(date[0:2]), u'*annee_' + date[0]]
126             self.meta.append('\n')
127             self.outfile.write('\n\n')
128             self.outfile.write(' '.join(self.meta).encode('utf8', errors='replace'))
129             self.outfile.write(' '.join(self.content).encode('utf8'))
130             self.content = []
131             self.meta = [u'****']
132             self.nb += 1
133             self.currentattr = None
134
135     def doinit(self, outfile):
136         self.currentattr = None
137         self.meta = [u'****']
138         self.content = []
139         self.nb = 0
140         self.outfile = outfile
141         print 'init ok'
142
143
144 def ParseEuropress(txtdir, fileout, encodage_in, encodage_out) :
145         files = []
146         if os.path.isdir(txtdir) :
147             for root, subfolders, subfiles in os.walk(txtdir) :
148                 nf = [os.path.join(root, f) for f in subfiles if f.split('.')[-1] in ['html', 'HTML'] ]
149                 nf.sort()
150                 files += nf
151             if len(files) == 0 :
152                 return 'nofile'
153         elif os.path.isfile(txtdir) :
154             files.append(txtdir)
155         tot = 0
156         parser = MyHTMLParser()
157         with open(fileout,'w') as outf :
158             for f in files :
159                 print f
160                 parser.doinit(outf)
161                 with codecs.open(f, 'rU', encodage_in) as infile :
162                     content = infile.read()
163                     content = HTMLParser().unescape(content)
164                 parser.feed(content)
165                 tot += parser.nb
166         return tot
167
168 #ParseEuropress('/home/pierre/fac/HDR/psychanalyse',
169 #               '/home/pierre/fac/HDR/psycha.txt', 'utf8', 'utf8')