root/BADataMunger/trunk/placesaver.py

Revision 1082, 32.8 kB (checked in by thomase, 1 year ago)

modify some logging and handle capitalization variation in feature types coming from GIS data (so now force ignore of capitalization of type when trying to mixmatch data)

  • Property svn:eol-style set to native
Line 
1 import logging
2 import re
3 from os.path import join
4 from StringIO import StringIO
5
6 import lxml.etree as etree
7
8 AWMC = "http://www.unc.edu/awmc/gazetteer/schemata/ns/0.3"
9 ADLGAZ = "http://www.alexandria.ucsb.edu/gazetteer/ContentStandard/version3.2/"
10 GEORSS = "http://www.georss.org/georss"
11 DC = "http://purl.org/dc/elements/1.1/"
12 XML = "http://www.w3.org/XML/1998/namespace"
13 TEI = "http://www.tei-c.org/ns/1.0"
14 XHTML = "http://www.w3.org/1999/xhtml"
15 MODS = "http://www.loc.gov/mods/v3"
16 XLINK = "http://www.w3.org/1999/xlink"
17
18 BIBLLIB = "/TomDocs/awmcwork/pleiadesact/svnbox/pleiades-bibliography/ids-and-titles.xml"
19
20
21 NSD = {'tei': TEI, 'mods': MODS}
22
23 BIBLURL = "http://www.unc.edu/awmc/pleiades/bibliography/"
24
25 WORKURLS = {
26     "RE":"http://www.unc.edu/awmc/pleiades/bibliography/re",
27     "NPauly":"http://www.unc.edu/awmc/pleiades/bibliography/npauly",
28     "KlPauly":"http://www.unc.edu/awmc/pleiades/bibliography/klpauly",
29     "PECS":"http://www.unc.edu/awmc/pleiades/bibliography/pecs"
30 }
31
32 periods = {
33     "A":"Archaic",
34     "C":"Classical",
35     "H":"Hellenistic (Roman Republic)",
36     "R":"Roman",
37     "L":"Late Antique"
38 }
39
40 confidence = {
41     "confident":"",
42     "less-confident":"?"
43 }
44
45 NSCLEANUPXSLT = 'nscleanup.xsl'
46 DESCXSLT = 'calc_Description.xsl'
47
48 def save_places_frank(self):
49     """Save all the places using the Pleiades frankenformat."""
50    
51     f = open(BIBLLIB)
52     content = f.read()
53     f.close()
54     biblib = etree.XML(content)
55
56     # iterate through the places list, creating a corresponding frankenfile for each place
57     places = self['places']
58     matchedplaces = [place for place in places if place.matched]
59     logging.info("BEGIN: attempting to save (in frankenformat) all %s matched and added places out of %s total places" % (len(matchedplaces), len(places)))
60     for i, place in enumerate(matchedplaces):
61        
62        
63         ge = etree.Element("{%s}geoEntity" % AWMC)
64        
65         # featureID
66         if place.tablei == -1 and place.rowi == -1:
67             placeid = "batlas-%s-anon-%s" % (place.map_number, place.anonsequence)
68         else:
69             placeid = "batlas-%s-%s-%s" % (place.map_number, place.tablei+1, place.rowi+1)
70         tag_fid = etree.Element("{%s}featureID" % ADLGAZ)
71         tag_fid.text = placeid
72         ge.append(tag_fid)
73        
74         # modernLocation (should be locationDescription, but anyway ...)
75         if len(place.locdesc) > 0:
76             tag_mloc = etree.Element("{%s}modernLocation" % AWMC)
77             tag_mloc.text = place.locdesc
78             ge.append(tag_mloc)
79        
80         # periods for the place
81         for tp in place.periods:
82             tag_tp = etree.Element("{%s}timePeriod" % ADLGAZ)
83             tag_tpn = etree.Element("{%s}timePeriodName" % ADLGAZ)
84             tpstring = periods[tp[0]]
85             if tp[1] == 'less-confident':
86                 tpstring += "?"
87             tag_tpn.text = tpstring
88             tag_tp.append(tag_tpn)
89             ge.append(tag_tp)
90            
91         # classification for the place
92         tag_cs = etree.Element("{%s}classificationSection" % ADLGAZ)
93         for tv in place.types:
94             tag_ct = etree.Element("{%s}classificationTerm" % ADLGAZ)
95             tag_ct.text = tv.lower()
96             tag_cs.append(tag_ct)
97             tag_css = etree.Element("{%s}classificationScheme" % ADLGAZ)
98             tag_csn = etree.Element("{%s}schemeName" % ADLGAZ)
99             tag_csn.text = "geoEntityType"
100             tag_css.append(tag_csn)
101             tag_cs.append(tag_css)
102
103         #tag_nassoc = etree.Element("{%s}nameAssociation" % AWMC)
104         #tag_nassoc.attrib['ref'] = pn.certainty
105         #tag_cs.append(tag_nassoc)
106         ge.append(tag_cs)
107
108            
109         # secondaryReferences
110         # first, recall our origins in the barrington atlas
111         tag_refs = etree.Element("{%s}secondaryReferences" % AWMC)
112         #tag_bibl = etree.Element("{%s}bibl" % TEI)
113         try:
114             thislabel = place.namestring.replace("/ ", "/")
115         except:
116             thislabel = ''
117         if len(thislabel) > 0:
118             findi = thislabel.find(u'\xA7')
119             if findi > -1:
120                 thislabel = thislabel[:findi-1].strip()
121             tag_bibl_xml = "<tei:bibl xmlns='%s' xmlns:tei='%s'><title>BAtlas</title> <biblScope>%s %s %s</biblScope></tei:bibl>" % (TEI, TEI, self.map_number, place.grid, thislabel)
122         else:
123             tag_bibl_xml = "<tei:bibl xmlns='%s' xmlns:tei='%s'><title>BAtlas</title> <biblScope>%s %s</biblScope></tei:bibl>" % (TEI, TEI, self.map_number, place.grid)
124        
125         tag_refs.append(etree.XML(tag_bibl_xml))
126        
127         # now, any other references
128         magicrefs = {}
129         #print len(place.placenames)
130         if len(place.placenames) == 1:
131             for ref in place.references:
132                 magicrefs[ref] = refmagic(ref, place.placenames[0].name)
133         elif len(place.placenames) > 1:
134             for ref in place.references:
135                 magicrefs[ref] = refmagic(ref, place.namestring)
136             for pn in place.placenames:
137                 for ref in pn.references:
138                     magicrefs[ref] = refmagic(ref, pn.name)
139
140            
141         if len(magicrefs) == 0 and len(place.references) > 0:
142             for ref in place.references:
143                 magicrefs[ref] = refmagic(ref, "")
144                            
145         for ref in place.references:
146             #print ">>> trying to write %s" % ref.encode('ascii', 'xmlcharrefreplace')
147             try:
148                 # need to fix this usage now that we have internal tagging
149                 tag_bibl_xml = "<tei:bibl xmlns='%s' xmlns:tei='%s'>%s</tei:bibl>" % (TEI, TEI, magicrefs[ref])
150                 if "tei:title" in tag_bibl_xml:
151                     pass
152                 else:
153                     print place.namestring.encode('ascii', 'xmlcharrefreplace')
154                     print ">>>> no title in: '%s'" % tag_bibl_xml.encode('ascii', 'xmlcharrefreplace')
155             except KeyError:
156                 print 'KeyError %s' % ref.encode('ascii', 'backslashreplace')
157                 print magicrefs
158             tag_refs.append(etree.XML(tag_bibl_xml))
159         ge.append(tag_refs)
160        
161         # spatial location - this only works for points!
162         for coordset in place.shapes:
163             tag_sl = etree.Element("{%s}spatialLocation" % ADLGAZ)
164             if self.mixer.geotype == 'esriGeometryPoint':
165                 tag_pt = etree.Element("{%s}point" % GEORSS)
166                 tag_pt.text = "%s %s" % (coordset[0][1], coordset[0][0])
167                 tag_sl.append(tag_pt)
168                 ge.append(tag_sl)
169             else:
170                 logging.warning("geotype not supported: %s" % self.mixer.geotype)
171            
172            
173            
174        
175        
176         # featureNames
177         for pn in place.placenames:
178            
179             tag_fn = etree.Element("{%s}featureName" % ADLGAZ)
180            
181             # transliteration
182             tag_translit = etree.Element("{%s}transliteration" % AWMC)
183             tag_translit.text = pn.name
184             tag_fn.append(tag_translit)
185            
186             # classificationSection
187             try:
188                 if place.types.index('people') != 0:
189                     nametype = 'ethnic'
190             except ValueError:
191                 nametype = 'geographic'
192             tag_cs = etree.Element("{%s}classificationSection" % ADLGAZ)
193             tag_ct = etree.Element("{%s}classificationTerm" % ADLGAZ)
194             tag_ct.text = nametype
195             tag_cs.append(tag_ct)
196             tag_css = etree.Element("{%s}classificationScheme" % ADLGAZ)
197             tag_csn = etree.Element("{%s}schemeName" % ADLGAZ)
198             tag_csn.text = "geoNameType"
199             tag_css.append(tag_csn)
200             tag_cs.append(tag_css)
201             if pn.inferred:
202                 tag_naspect = etree.Element("{%s}nameAspect" % AWMC)
203                 tag_naspect.attrib['ref'] = 'na-inferred'
204                 tag_cs.append(tag_naspect)
205             if pn.completeness != 'complete':
206                 tag_naspect = etree.Element("{%s}nameAspect" % AWMC)
207                 tag_naspect.attrib['ref'] = 'na-reconstructed'
208                 tag_cs.append(tag_naspect)
209             if pn.accuracy != 'accurate':
210                 tag_naspect = etree.Element("{%s}nameAspect" % AWMC)
211                 tag_naspect.attrib['ref'] = 'na-inaccurate'
212                 tag_cs.append(tag_naspect)
213             tag_nassoc = etree.Element("{%s}nameAssociation" % AWMC)
214             tag_nassoc.attrib['ref'] = pn.certainty
215             tag_cs.append(tag_nassoc)
216             tag_fn.append(tag_cs)
217
218             # timePeriods for the name
219             for tp in pn.periods:
220                 tag_tp = etree.Element("{%s}timePeriod" % ADLGAZ)
221                 tag_tpn = etree.Element("{%s}timePeriodName" % ADLGAZ)
222                 tpstring = periods[tp[0]]
223                 if tp[1] == 'less-confident':
224                     tpstring += "?"
225                 tag_tpn.text = tpstring
226                 tag_tp.append(tag_tpn)
227                 tag_fn.append(tag_tp)
228                
229             # secondary references for the name
230             if len(pn.references) > 0:
231                 tag_refs = etree.Element("{%s}secondaryReferences" % AWMC)
232                 for ref in pn.references:
233                     tag_bibl_xml = "<tei:bibl xmlns='%s' xmlns:tei='%s'>%s</tei:bibl>" % (TEI, TEI, magicrefs[ref])
234                     if "tei:title" in tag_bibl_xml:
235                         pass
236                     else:
237                         print place.namestring.encode('ascii', 'xmlcharrefreplace')
238                         print ">>>> no title in: '%s'" % tag_bibl_xml.encode('ascii', 'xmlcharrefreplace')
239                        
240                     tag_refs.append(etree.XML(tag_bibl_xml))
241                    
242                 tag_fn.append(tag_refs)
243
244                
245             ge.append(tag_fn)
246            
247                
248         for c in self.creators:
249             tag_c = etree.Element("{%s}creator" % DC)
250             tag_c.text = c
251             ge.append(tag_c)
252         for c in self.contributors:
253             tag_c = etree.Element("{%s}contributor" % DC)
254             tag_c.text = c
255             ge.append(tag_c)
256         if len(self.rights) > 0:
257             tag_r = etree.Element("{%s}rights" % DC)
258             tag_r.text = self.rights
259             ge.append(tag_r)
260            
261         # try to slap ids on the bibliographic titles
262        
263         for bibtitle in ge.xpath("//tei:title", NSD):
264             thisxpath = u"//entry[descendant::short-title='%s']/id" % unicode(bibtitle.text)
265             logging.info ("%s seeking a match for short title '%s'" % (place.namestring.encode('ascii', 'xmlcharrefreplace'), bibtitle.text.encode('ascii', 'xmlcharrefreplace')))
266             blah = biblib.xpath(thisxpath)[0]
267             bibtitle.attrib["{%s}type" % XLINK] = 'simple'
268             bibtitle.attrib["{%s}href" % XLINK] = "%s%s.html" % (BIBLURL, blah.text)
269    
270         # lxml etree makes ugly xml with lots of unnecessarily repeated namespace attributes
271         # so clean it up
272         #print ge
273         cleantree = do_nscleanup(self['contextpath'], ge)
274        
275         # calculate a description
276         cleantree = do_description(self['contextpath'], cleantree)
277         #print etree.tostring(cleantree).encode('ascii', 'xmlcharrefreplace')
278        
279         # encode the content as utf8 and save to file
280         pcontent = etree.tostring(cleantree).encode('utf-8')
281         destfile = "%s-frank.xml" % placeid
282         g = open(join(self['destdir'], destfile),'w')
283         g.write(pcontent)
284         g.close()
285        
286     logging.info("DONE saving in frankenformat")
287    
288 def save_places_tei(self):
289     """Save all the places as a TEI place file (P5 draft)."""
290    
291     # iterate through the places list, creating a corresponding TEI file
292     places = self['places']
293     tag_listPlace = etree.Element("{%s}listPlace" % TEI)
294     for i, place in enumerate(places):
295
296         # the place tag itself
297         tag_place = etree.Element("{%s}place" % TEI)
298         placeid = "batlas-%s-%s-%s" % (place.map_number, place.tablei+1, place.rowi+1)
299         tag_place.attrib['xml:id'] = placeid
300         tag_listPlace.append(tag_place)
301        
302         # handle typing vs. consolidated tables and unlocateds
303         if place.type == 'name' or place.type == 'numbered' or place.type == 'unlocated':
304             tag_place.attrib['type'] = 'undefined'
305             tag_note = etree.Element("{%s}note" % TEI)
306             tag_note.attrib['type'] = 'origin'
307             tag_note.attrib['n'] = place.type
308             tag_note.text = "Data originated from a BAtlas '%s' table." % place.type
309             tag_place.append(tag_note)
310         else:
311             tag_place.attrib['type'] = place.type
312         if place.type == 'numbered':
313             tag_note = etree.Element("{%s}note" % TEI)
314             tag_note.attrib['type'] = 'number'
315             tag_note.text = place.number
316             tag_place.append(tag_note)
317        
318         # names
319         do_placenames(tag_place, place, placeid)
320        
321         # location elements for unlocated places
322         do_locations (tag_place, place, placeid)
323        
324         # periods
325         # NOT DONE
326        
327         # references
328         do_references (tag_place, place, placeid)
329        
330        
331        
332     # lxml etree makes ugly xml with lots of unnecessarily repeated namespace attributes
333     # so clean it up
334     cleantree = do_nscleanup(self['contextpath'], tag_listPlace)
335    
336     # encode the content as utf8 and save to file
337     pcontent = etree.tostring(cleantree).encode('utf-8')
338     destfile = "%s-places-tei.xml" % self['filenameroot']
339     g = open(join(self['destdir'], destfile),'w')
340     g.write(pcontent)
341     g.close()
342
343 def do_placenames(parent, place, placeid, nameType=None):
344     names = place.placenames
345     for i, name in enumerate(names):
346        
347         # the name tag itself
348         tag_name = etree.Element("{%s}name" % TEI)
349         nameid = "%s-n%s" % (placeid, i+1)
350         tag_name.attrib['xml:id'] = nameid
351         tag_name.text = name.name
352         parent.append(tag_name)
353        
354         # completeness
355         if name.completeness != 'complete':
356             tag_note = etree.Element("{%s}note" % TEI)
357             tag_note.attrib['type'] = 'certainty'
358             tag_note.attrib['n'] = 'name-completeness'
359             tag_note.attrib['target'] = "#%s" % nameid
360             tag_note.text = name.completeness
361             parent.append(tag_note)
362            
363         # accuracy
364         if name.accuracy != 'accurate':
365             tag_note = etree.Element("{%s}note" % TEI)
366             tag_note.attrib['type'] = 'certainty'
367             tag_note.attrib['n'] = 'name-accuracy'
368             tag_note.attrib['target'] = "#%s" % nameid
369             tag_note.text = name.accuracy
370             parent.append(tag_note)
371            
372         # association confidence????
373         # NOT DONE
374            
375         # periods for name
376         # NOT DONE
377        
378 def do_locations(parent, place, placeid):
379
380     if len(place.locdesc) > 0:
381         tag_location = etree.Element("{%s}location" % TEI)
382         tag_location.text = place.locdesc
383         parent.append(tag_location)
384     elif place.type == 'road':
385         tag_location = etree.Element("{%s}location" % TEI)
386         tag_location.text = u' \xae '.join(place.itinerary)
387         parent.append(tag_location)
388     elif place.type == 'unlocated':
389         tag_location = etree.Element("{%s}location" % TEI)
390         tag_location.text = "unlocated"
391         parent.append(tag_location)
392    
393 def do_references(parent, place, placeid):
394    
395     for ref in place.references:
396         tag_bibl = etree.Element("{%s}bibl" % TEI)
397         tag_bibl.text = ref
398         parent.append(tag_bibl)
399
400
401
402 # old junk from MODS below         
403 def do_title(content, titleType=None):
404     titleInfo = etree.Element("{%s}titleInfo" % MODS)
405     if titleType:
406         titleInfo.attrib['type'] = titleType
407     title = etree.Element("{%s}title" % MODS)
408     title.text = unicode(content)
409     titleInfo.append(title)
410     return titleInfo
411    
412 def do_citation(content):
413     abstract = etree.Element("{%s}abstract" % MODS)
414     abstract.append(content)
415     return abstract
416    
417 def do_nscleanup(contextpath, source):
418     xslpath = join(contextpath, NSCLEANUPXSLT)
419     result = do_transform(xslpath, source)
420     return result
421    
422 def do_description(contextpath, source):
423     xslpath = join(contextpath, DESCXSLT)
424     result = do_transform(xslpath, source)
425     return result   
426    
427 def do_transform(xslpath, source):
428     xslt_doc = etree.parse(xslpath)
429     transform = etree.XSLT(xslt_doc)
430     tsource = transform(source)
431     stringt = etree.tostring(tsource)
432     result = etree.XML(stringt)
433     return result
434    
435 def refmagic(ref, pname):
436     """tag up our references in tei, preparatory to assigning ids to titles
437    
438     >>> class Placename: name = ''
439     >>> pn = Placename()
440     >>> pn.name = 'Aphrodisias'
441     >>> refmagic('Ptol. 4.4.7', pn)
442     "<tei:title type='abbreviated'>Ptol.</tei:title> <tei:biblScope>4.4.7</tei:biblScope>"
443     >>> refmagic('ItMiller 877', pn)
444     "<tei:title type='abbreviated'>ItMiller</tei:title> <tei:biblScope>877</tei:biblScope>"
445     >>> refmagic('Stucchi 1975, 359', pn)
446     "<tei:title type='abbreviated'>Stucchi 1975</tei:title> <tei:biblScope type='pages'>359</tei:biblScope>"
447     >>> refmagic('Purcaro Pagano 1976, 326', pn)
448     "<tei:title type='abbreviated'>Purcaro Pagano 1976</tei:title> <tei:biblScope type='pages'>326</tei:biblScope>"
449     >>> refmagic('Carter 1963, 19-20', pn)
450     "<tei:title type='abbreviated'>Carter 1963</tei:title> <tei:biblScope type='pages'>19-20</tei:biblScope>"
451     >>> refmagic('Humphrey 1976', pn)
452     "<tei:title type='abbreviated'>Humphrey 1976</tei:title>"
453     >>> refmagic('Scarin 1937, 45-81, 95-107, 121-25', pn)
454     "<tei:title type='abbreviated'>Scarin 1937</tei:title> <tei:biblScope type='pages'>45-81, 95-107, 121-25</tei:biblScope>"
455     >>> refmagic('EncBerb 7', pn)
456     "<tei:title type='abbreviated' key='encberb'>EncBerb</tei:title> <tei:biblScope type='volumes'>7</tei:biblScope> <tei:biblScope type='lemma'>Aphrodisias</tei:biblScope>"
457     >>> refmagic('EncBerb 8 Afrodisias', pn)
458     "<tei:title type='abbreviated' key='encberb'>EncBerb</tei:title> <tei:biblScope type='volumes'>8</tei:biblScope> <tei:biblScope type='lemma'>Afrodisias</tei:biblScope>"
459     >>> refmagic('TIR Cyrene', pn)
460     "<tei:title type='abbreviated'>TIR Cyrene</tei:title>"
461     >>> refmagic('von Aulock 1977, 20-22', pn)
462     "<tei:title type='abbreviated'>von Aulock 1977</tei:title> <tei:biblScope type='pages'>20-22</tei:biblScope>"
463     >>> refmagic('von Aulock 1977', pn)
464     "<tei:title type='abbreviated'>von Aulock 1977</tei:title>"
465     >>> refmagic('TAM 2.3, 318-22', pn)
466     "<tei:title type='abbreviated'>TAM</tei:title> <tei:biblScope type='volumes'>2.3</tei:biblScope>, <tei:biblScope type='pages'>318-22</tei:biblScope>"
467     >>> refmagic('StadtMM 241-42', pn)
468     "<tei:title type='abbreviated'>StadtMM</tei:title> <tei:biblScope>241-42</tei:biblScope>"
469     >>> refmagic('TAM 2.2, 188', pn)
470     "<tei:title type='abbreviated'>TAM</tei:title> <tei:biblScope type='volumes'>2.2</tei:biblScope>, <tei:biblScope type='pages'>188</tei:biblScope>"
471     >>> refmagic('NPauly Kelainai', pn)
472     "<tei:title type='abbreviated'>NPauly</tei:title> <tei:biblScope type='lemma'>Kelainai</tei:biblScope>"
473     >>> refmagic('RE', pn)
474     "<tei:title type='abbreviated' key='re'>RE</tei:title> <tei:biblScope type='lemma'>Aphrodisias</tei:biblScope>"
475     >>> refmagic('NPauly', pn)
476     "<tei:title type='abbreviated' key='npauly'>NPauly</tei:title> <tei:biblScope type='lemma'>Aphrodisias</tei:biblScope>"
477     >>> refmagic('KlPauly', pn)
478     "<tei:title type='abbreviated' key='klpauly'>KlPauly</tei:title> <tei:biblScope type='lemma'>Aphrodisias</tei:biblScope>"
479     >>> refmagic('PECS', pn)
480     "<tei:title type='abbreviated' key='pecs'>PECS</tei:title> <tei:biblScope type='lemma'>Aphrodisias</tei:biblScope>"
481     >>> refmagic('PECS Elmali', pn)
482     "<tei:title type='abbreviated' key='pecs'>PECS</tei:title> <tei:biblScope type='lemma'>Elmali</tei:biblScope>"
483     >>> refmagic('RE 1', pn)
484     "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>Aphrodisias 1</tei:biblScope>"
485     >>> refmagic('NPauly 1', pn)
486     "<tei:title type='abbreviated'>NPauly</tei:title> <tei:biblScope type='lemma'>Aphrodisias 1</tei:biblScope>"
487     >>> refmagic('KlPauly 1', pn)
488     "<tei:title type='abbreviated'>KlPauly</tei:title> <tei:biblScope type='lemma'>Aphrodisias 1</tei:biblScope>"
489     >>> refmagic('RE Suppl. 1', pn)
490     "<tei:title type='abbreviated' key='re'>RE</tei:title> Suppl. <tei:biblScope type='supplement'>1</tei:biblScope> <tei:biblScope type='lemma'>Aphrodisias</tei:biblScope>"
491     >>> refmagic('RE Sozopolis', pn)
492     "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>Sozopolis</tei:biblScope>"
493     >>> refmagic('RE Sozopolis 7', pn)
494     "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>Sozopolis 7</tei:biblScope>"
495     >>> refmagic('TIB Phrygien 387-8', pn)
496     "<tei:title type='abbreviated'>TIB Phrygien</tei:title> <tei:biblScope>387-8</tei:biblScope>"
497     >>> refmagic('Strabo 14.2.2', pn)
498     "<tei:title type='abbreviated'>Strabo</tei:title> <tei:biblScope>14.2.2</tei:biblScope>"
499     >>> refmagic('RE Arykandos', pn)
500     "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>Arykandos</tei:biblScope>"
501     >>> refmagic('Pliny, NH 5.131', pn)
502     "<tei:title type='abbreviated'>Pliny, NH</tei:title> <tei:biblScope>5.131</tei:biblScope>"
503     >>> refmagic('RE Suppl. 12 Attaleia', pn)
504     "<tei:title type='abbreviated' key='re'>RE</tei:title> Suppl. <tei:biblScope type='supplement'>12</tei:biblScope> <tei:biblScope type='lemma'>Attaleia</tei:biblScope>"
505     >>> refmagic('Skylax 100', pn)
506     "<tei:title type='abbreviated'>Skylax</tei:title> <tei:biblScope>100</tei:biblScope>"
507     >>> refmagic('RE Tauros 5, col. 42', pn)
508     "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>Tauros 5</tei:biblScope>, col. <tei:biblScope type='columns'>42</tei:biblScope>"
509     >>> refmagic('MAMA 7, xiii', pn)
510     "<tei:title type='abbreviated'>MAMA</tei:title> <tei:biblScope type='volumes'>7</tei:biblScope>, <tei:biblScope type='pages'>xiii</tei:biblScope>"
511     >>> refmagic('MAMA 8.348, p. xv', pn)
512     "<tei:title type='suspect'>MAMA 8.348, p. xv</tei:title>"
513     >>> refmagic('GGM I, 74', pn)
514     "<tei:title type='abbreviated'>GGM</tei:title> <tei:biblScope type='volumes'>I</tei:biblScope>, <tei:biblScope type='pages'>74</tei:biblScope>"
515     >>> refmagic('FOA VIII, 9',  pn)
516     "<tei:title type='abbreviated'>FOA</tei:title> <tei:biblScope type='volumes'>VIII</tei:biblScope>, <tei:biblScope type='pages'>9</tei:biblScope>"
517     >>> refmagic('RE XVIII.1, cols. 1098-1105 demos Ormeleon', pn)
518     "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='volumes'>XVIII.1</tei:biblScope>, cols. <tei:biblScope type='columns'>1098-1105</tei:biblScope> <tei:biblScope type='lemma'>demos Ormeleon</tei:biblScope>"
519     >>> refmagic('Robert, Hell. 10, 207-208', pn)
520     "<tei:title type='abbreviated'>Robert, Hell.</tei:title> <tei:biblScope type='volumes'>10</tei:biblScope>, <tei:biblScope type='pages'>207-208</tei:biblScope>"
521     >>> refmagic('IG I(3) 71 (lines 153-54)', pn)
522     "<tei:title type='abbreviated'>IG I(3)</tei:title> <tei:biblScope type='numbers'>71</tei:biblScope> (lines <tei:biblScope type='lines'>153-54</tei:biblScope>)"
523     """
524     try:
525         if  '/' in pname:
526             spname = pname.split('/')[0].strip()
527         else:
528             spname = pname
529     except:
530         spname = ''
531     if ref == "RE":
532         result = "<tei:title type='abbreviated' key='re'>RE</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>" % spname
533     elif ref == "NPauly":
534         result = "<tei:title type='abbreviated' key='npauly'>NPauly</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>" % spname
535     elif ref == "KlPauly":
536         result = "<tei:title type='abbreviated' key='klpauly'>KlPauly</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>" % spname
537     elif ref == "PECS":
538         result = "<tei:title type='abbreviated' key='pecs'>PECS</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>" % spname
539     elif ref == "StByz":
540         result = "<tei:title type='abbreviated' key='stbyz'>StByz</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>" % spname
541     else:
542         # note: the order of the following tests is important!
543         wodge = \
544             [
545                (   "^RE (.+) \(\?\)$",
546                    "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope> (?)",
547                    ('1')
548                ),
549                (   "^MAMA (\d+), ([\d\-]+) \(no. (\d+)\)$",
550                    "<tei:title type='abbreviated'>MAMA</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, <tei:biblScope type='pages'>%s</tei:biblScope> (no. <tei:biblScope type='numbers'>%s</tei:biblScope>)",
551                    ('1', '2', '3')
552                ),
553                (   "^SEG (\d+) \(([12][7890]\\d\\d)\) no. (\d+)$",
554                    "<tei:title type='abbreviated'>SEG</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, (<tei:date>%s</tei:date>) no. <tei:biblScope type='numbers'>%s</tei:biblScope>)",
555                    ('1', '2', '3')
556                ),
557                (
558                    "^AnatSt (\d+) \(([12][7890]\\d\\d)\) (.+)$",
559                    "<tei:title type='abbreviated'>AnatSt</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope> <tei:date>%s</tei:date> <tei:biblScope>%s</tei:biblScope>",
560                    ('1', '2', '3')
561                ),
562                (
563                    "^IG I\(3\) ([^ ]+) \(lines (.+)\)$",
564                    "<tei:title type='abbreviated'>IG I(3)</tei:title> <tei:biblScope type='numbers'>%s</tei:biblScope> (lines <tei:biblScope type='lines'>%s</tei:biblScope>)",
565                    ('1', '2')
566                ),
567                (
568                    "^(Procop.|Ptol.), (Aed.|Geog.) ([\d\.\-]+)$",
569                    "<tei:title type='abbreviated'>%s, %s</tei:title> <tei:biblScope>%s</tei:biblScope>",
570                    ('1', '2', '3')               
571                ),
572                (
573                    "^Robert, (Hell.|OMS) (\d+), ([\d\-]+)$",
574                    "<tei:title type='abbreviated'>Robert, %s</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, <tei:biblScope type='pages'>%s</tei:biblScope>",
575                    ('1', '2', '3')
576                ),
577                (
578                    "^RE ([IXV]+\.?\d*), (cols?\.) ([\d\-,]+) (.+)$",
579                    "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, %s <tei:biblScope type='columns'>%s</tei:biblScope> <tei:biblScope type='lemma'>%s</tei:biblScope>",
580                    ('1', '2', '3', '4')
581                ),
582                (
583                    "^(RE) ([^,]+), cols?\. ([\d-]+)$",
584                    "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>, cols. <tei:biblScope type='columns'>%s</tei:biblScope>",
585                    ('2', '3')
586                ),
587                (
588                    "^(RE) ([^\d]+) (\d+), (cols?\.) (\d+)$",
589                    "<tei:title type='abbreviated'>RE</tei:title> <tei:biblScope type='lemma'>%s %s</tei:biblScope>, %s <tei:biblScope type='columns'>%s</tei:biblScope>",
590                    ('2', '3', '4', '5')
591                ),
592                (
593                    "^(RE|NPauly|KlPauly) (\d+)$",
594                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='lemma'>%s %s</tei:biblScope>",
595                    ('1', 'name','2')
596                ),
597                (
598                    "^(RE|NPauly|KlPauly) ([^ \d]+)$",
599                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>",
600                    ('1', '2')
601                ),
602                (
603                    "^(RE) Suppl. (\d+)$",
604                    "<tei:title type='abbreviated'>RE</tei:title> Suppl. <tei:biblScope type='supplement'>%s</tei:biblScope> <tei:biblScope type='lemma'>%s</tei:biblScope>",
605                    ('2', 'name')
606                ),
607                (
608                    "^(RE) Suppl. (\d+) ([^ \d]+)$",
609                    "<tei:title type='abbreviated'>RE</tei:title> Suppl. <tei:biblScope type='supplement'>%s</tei:biblScope> <tei:biblScope type='lemma'>%s</tei:biblScope>",
610                    ('2', '3')
611                ),
612                (
613                    "^(RE) Suppl. (\d+) ([^ \d]+) (\d+)$",
614                    "<tei:title type='abbreviated'>RE</tei:title> Suppl. <tei:biblScope type='supplement'>%s</tei:biblScope> <tei:biblScope type='lemma'>%s %s</tei:biblScope>",
615                    ('2', '3', '4')
616                ),
617                (
618                    "^(RE|NPauly|KlPauly) ([^\d\.]+) (\d+)$",
619                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='lemma'>%s %s</tei:biblScope>",
620                    ('1', '2', '3')
621                ),
622                (
623                    "^(RE|NPauly|KlPauly) ([^\d]+)$",
624                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>",
625                    ('1', '2')
626                ),
627                (
628                    "^(PECS|StByz) ([^ \d]+)$",
629                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='lemma'>%s</tei:biblScope>",
630                    ('1', '2')
631                ),
632                (
633                    "^(EncBerb) (\d+)$",
634                    "<tei:title type='abbreviated'>EncBerb</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope> <tei:biblScope type='lemma'>%s</tei:biblScope>",
635                    ('2', 'name')
636                ),
637                (
638                    "^(EncBerb) (\d+) (.*)$",
639                    "<tei:title type='abbreviated'>EncBerb</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope> <tei:biblScope type='lemma'>%s</tei:biblScope>",
640                    ('2', '3')
641                ),
642                (
643                   "^([^\d]+) ([12][7890]\d\d) ([IVX\d]+), (.*)$",
644                   "<tei:title type='abbreviated'>%s %s</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, <tei:biblScope type='pages'>%s</tei:biblScope>",
645                   ('1', '2', '3', '4')
646                ),
647                (
648                   "^([^\d]+) ([12][7890]\d\d[a-z]?), (.*)$",
649                   "<tei:title type='abbreviated'>%s %s</tei:title>, <tei:biblScope type='pages'>%s</tei:biblScope>",
650                   ('1', '2', '3')
651                ),
652                (
653                   "^([^\d]+) ([12][7890]\d\d)$",
654                   "<tei:title type='abbreviated'>%s %s</tei:title>",
655                   ('1', '2')
656                ),
657                (
658                    "^([A-Z]+) ([\dXVI\.]+), ([ \d\-,]+)$",
659                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, <tei:biblScope type='pages'>%s</tei:biblScope>",
660                    ('1', '2', '3')           
661                ),
662                (
663                    "^([^\.][^ \.]*\.*) ([\d\.\-]+)$",
664                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope>%s</tei:biblScope>",
665                    ('1', '2')
666                ),
667                (
668                    "^([^ \d]+) ([\d\.]+), ([\d\-xvi]+)$",
669                    "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope type='volumes'>%s</tei:biblScope>, <tei:biblScope type='pages'>%s</tei:biblScope>",
670                    ('1', '2', '3')
671                ),
672                (
673                     "^([^ \d]+) (\d+)$",
674                     "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope>%s</tei:biblScope>",
675                     ('1', '2')
676                ),
677                (
678                     "^([^\d]+) ([\d-]+)$",
679                     "<tei:title type='abbreviated'>%s</tei:title> <tei:biblScope>%s</tei:biblScope>",
680                     ('1', '2')
681                ),
682                (
683                    "^([^\.][^ \.]*\.*), ([A-Z]+) ([\d\.\-]+)$",
684                    "<tei:title type='abbreviated'>%s, %s</tei:title> <tei:biblScope>%s</tei:biblScope>",
685                    ('1', '2', '3')
686                ),
687                (   "^(D.H. French|C. Foss|F. Hild|J.B. Ward-Perkins)$",
688                    "unpublished work of %s",
689                    ('1')
690                ),
691                
692                
693             ]
694         for w in wodge:
695             result = refmagicptrn(ref, pname, w[0], w[1], w[2])
696             if len(result) != 0:
697                 break
698     if len(result) == 0:
699         if ref.find('.') != -1 or ref.find(',') != -1:
700             result = "<tei:title type='suspect'>%s</tei:title>" % ref
701         else:
702             result = "<tei:title type='abbreviated'>%s</tei:title>" % ref
703     return result
704    
705 def refmagicptrn(ref, pname, ptrn, tmplt, gmap):
706     result = ""
707     m = re.match(ptrn, ref)
708     if m:
709         data = []
710         for g in gmap:
711             if g=='name':
712                 data.append(pname)
713             elif g.startswith('http:'):
714                 data.append(g)
715             else:
716                 data.append(m.group(eval(g)))
717         #print tmplt
718         #print data
719         result = tmplt % tuple(data)
720     return result
721    
722 def _test():
723     import doctest
724     doctest.testmod()
725
726 if __name__ == "__main__":
727     _test()
728    
Note: See TracBrowser for help on using the browser.