Merge branch 'master' of 192.168.0.2:/home/pouns/iramuteqNG
[iramuteq] / parse_factiva_xml.py
1 #!/bin/env python
2 # -*- coding: utf-8 -*-
3 #Author: Pierre Ratinaud
4 #Copyright (c) 2008-2010 Pierre Ratinaud
5 #Lisense: GNU/GPL
6
7 import xml.dom.minidom
8 import wx.lib.sized_controls as sc
9 import wx.lib.filebrowsebutton as filebrowse
10 import os
11 import codecs
12 import sys
13 import re
14 import wx
15
16
17 def ParseDocument(filename) :
18     print filename
19     with codecs.open(filename, 'r', 'utf-8') as f :
20         content = f.read()
21     content = content.replace('<hlt>', ' ').replace('</hlt>', ' ')
22     dom = xml.dom.minidom.parseString(content.encode("utf-8"))
23     result = []
24     articles = dom.getElementsByTagName("article")
25     i = 0
26     for article in articles :
27         headline = article.getElementsByTagName("headline")
28         if headline != [] :
29             para_headline = headline[0].getElementsByTagName("paragraph")
30             val_headline = [val.firstChild.nodeValue.replace('\n', ' ') for val in para_headline]
31         else :
32             val_headline = []
33         leadParagraph = article.getElementsByTagName("leadParagraph")
34         if leadParagraph != [] :
35             para_leadParagraph = leadParagraph[0].getElementsByTagName("paragraph")
36             val_leadParagraph = [val.firstChild.nodeValue.replace('\n', ' ') for val in para_leadParagraph]
37         else :
38             val_leadParagraph = []
39         publicationDate = article.getElementsByTagName("publicationDate")
40         if publicationDate != [] :
41             para_publicationDate = publicationDate[0].getElementsByTagName("date")
42             if para_publicationDate == [] :
43                 para_publicationDate = publicationDate[0].getElementsByTagName("dateTime")
44             val_publicationDate = [val.firstChild.nodeValue.replace('\n', ' ') for val in para_publicationDate]
45         else :
46             val_publicationDate = []
47         sourceName = article.getElementsByTagName("sourceName")
48         if sourceName != [] :
49             val_sourceName = sourceName[0].firstChild.nodeValue.replace('\n', ' ')
50         else :
51             val_sourceName = INCONNU
52         tailParagraphs = article.getElementsByTagName("tailParagraphs")
53         if tailParagraphs != [] :
54             para_tailParagraphs = tailParagraphs[0].getElementsByTagName("paragraph")
55             val_tailParagraphs = [val.firstChild.nodeValue.replace('\n', ' ') for val in para_tailParagraphs]
56         else :
57             val_tailParagraphs = []
58         inter = [' '.join(val_headline), val_sourceName,' '.join(val_publicationDate), ' '.join(val_leadParagraph), ' '.join(val_tailParagraphs)]
59         inter = [re.sub(ur'[ "\n\r]+', ' ',  val).replace('"',' ').replace('\n', ' ').replace('\r', ' ')  for val in inter]
60         #inter = ['"' + val +'"' for val in inter]
61         result.append(inter)
62     return result
63     
64 def getcorpus_from_xml(xmldir, corpus_out):
65     files = os.listdir(xmldir)
66     files = [os.path.join(xmldir,file) for file in files if os.path.splitext(file)[1] == '.xml']
67     if len(files) == 0 :
68         return 'nofile'
69     result = []
70     fileout = codecs.open(corpus_out, 'w', 'utf-8')
71     for file in files :
72         rs = ParseDocument(file)
73         #dates = [row[2].split('-') for row in rs]
74         #dates = [[date[0],date[1],date[2].split('T')[0]] for date in dates]
75         #txt = '\n'.join(['\n'.join([' '.join([u'****', '*%s' % row[1].replace(' ','_').replace('\'','_'), '*%s' % row[2].replace('-','_')]), row[3], row[4]]) for row in rs])
76         #avec la date decompose
77         txt = '\n'.join(['\n'.join([' '.join([u'****', '*s_%s' % row[1].replace(' ','').replace('\'',''), '*annee_%s' % row[2].split('-')[0], '*mois_%s' % row[2].split('-')[1], '*jour_%s' % row[2].split('-')[2].split('T')[0]]), row[3], row[4]]) for row in rs])
78         fileout.write(txt+'\n\n')
79     fileout.close()
80     return 'ok'
81
82 class PrefImport(wx.Dialog):
83     def __init__(self, parent, size=wx.DefaultSize, pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE):
84         pre = wx.PreDialog()
85         pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
86         pre.Create(parent, -1, '', pos, size, style)
87         self.PostCreate(pre)
88
89         self.parent = parent
90         self.txt1 = wx.StaticText(self, -1, u"Répertoire des fichiers xml")
91         self.dbb = filebrowse.DirBrowseButton(self, -1, size=(450, -1), changeCallback = self.fbbCallback)
92         self.dbb.SetLabel("")
93         self.txt2 = wx.StaticText(self, -1, u"Fichier en sortie")
94         self.fbb = filebrowse.FileBrowseButton(self, -1, size=(450, -1), fileMode = 2)
95         self.fbb.SetLabel("")
96
97         self.btnsizer = wx.StdDialogButtonSizer()
98         btn_ok = wx.Button(self, wx.ID_OK)
99         btn = wx.Button(self, wx.ID_CANCEL)
100         self.btnsizer.AddButton(btn_ok)
101         self.btnsizer.AddButton(btn)
102         self.btnsizer.Realize()
103
104
105         self.Bind(wx.EVT_BUTTON, self.checkfile, btn_ok)
106
107         #self.SetButtonSizer(self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL))
108         self.Bind(wx.EVT_BUTTON, self.checkfile)
109
110         self. __do_layout()
111         #self.Fit()
112         self.SetMinSize(self.GetSize())
113     
114     def __do_layout(self):
115         sizer = wx.BoxSizer(wx.VERTICAL)
116         grid_sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
117         grid_sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
118         grid_sizer_1.Add(self.txt1, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, 0)
119         grid_sizer_1.Add(self.dbb, 2, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, 0)
120         grid_sizer_2.Add(self.txt2, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, 0)
121         grid_sizer_2.Add(self.fbb, 2, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, 0)
122         sizer.Add(grid_sizer_1, 0,  wx.EXPAND, 0)
123         sizer.Add(grid_sizer_2, 0,  wx.EXPAND, 0)
124         sizer.Add(self.btnsizer, 0,  wx.EXPAND, 0)
125         self.SetSizer(sizer)
126         sizer.Fit(self)
127         self.Layout()
128
129    
130     def fbbCallback(self, evt):
131         if self.fbb.GetValue() == "" :
132              self.fbb.SetValue(os.path.join(self.dbb.GetValue(), 'corpus.txt'))
133         #self.log.write('FileBrowseButton: %s\n' % evt.GetString())
134
135     def checkfile(self, evt) :
136         if evt.GetId() == wx.ID_OK :
137             if self.dbb.GetValue() != "" :
138                 if os.path.exists(self.fbb.GetValue()):
139                     dlg = wx.MessageDialog(self, 
140                     u"%s\nCe fichier existe, continuer quand même ?" % self.fbb.GetValue(), 'ATTENTION', wx.NO | wx.YES | wx.ICON_WARNING)
141                     dlg.CenterOnParent()
142                     if dlg.ShowModal() not in [wx.ID_NO, wx.ID_CANCEL]:
143                         self.EndModal(wx.ID_OK)
144                 else :
145                     self.EndModal(wx.ID_OK)
146             else :
147                 dlg = wx.MessageDialog(self, u"Vous devez choisir le répertoire contenant le ou les fichier(s) xml", 'ATTENTION', wx.OK | wx.ICON_WARNING)
148                 dlg.CenterOnParent()
149                 dlg.ShowModal()
150
151         else :
152             self.EndModal(wx.ID_CANCEL)
153
154
155
156 class ImportFactiva():
157     def __init__(self,parent):
158        self.dial =  PrefImport(parent)
159        self.dial.CenterOnParent()
160        val = self.dial.ShowModal()
161        if val == wx.ID_OK :
162            xmldir = self.dial.dbb.GetValue()
163            corp_out = self.dial.fbb.GetValue()
164            res = getcorpus_from_xml(xmldir, corp_out)
165            if res != 'ok' :
166                 dlg = wx.MessageDialog(parent, u"Pas de fichier \'.xml\' dans %s" % xmldir, 'ATTENTION', wx.OK | wx.NO_DEFAULT | wx.ICON_WARNING)
167                 dlg.CenterOnParent()
168                 dlg.ShowModal()
169            else :
170                 parent.filename = corp_out
171                 parent.OpenText()