expoweb/noinfo/make-areaindices.py

86 lines
2.2 KiB
Python

import re, sys, os
from string import join
import csv
areas = []
caves = []
WARNING_MESSAGE="""
<!-- Do not edit this file! It is auto-generated. Edit the template file noinfo/areapage_skeletons/%s instead. -->
"""
TABLE_PREAMBLE="""
<table class="centre" border="1">
<tr><th align="center">Number</th><th>Name</th></tr>"""
TABLE_LINE="""
<tr><td align="right"><a id="id%(lcnumber)s">%(number)s</a></td><td><a href="%(url)s">%(name)s</a></td></tr>
"""
TABLE_POSTAMBLE="""
</table>"""
def main():
read_cavetab()
create_indices()
def read_cavetab():
cavetabfile = file("noinfo/CAVETAB2.CSV")
fieldnames = chomp(cavetabfile.next()).replace('"','').split(",")
cavetab = csv.DictReader(cavetabfile, fieldnames)
for cave in cavetab:
if(cave["Multiple entrances"] not in ("", "yes")):
continue
area = cave["Area"]
if(area not in areas): areas.append(area)
caves.append(cave)
def create_indices():
files_tohandle = os.listdir("noinfo/areapage_skeletons/")
for f in files_tohandle:
create_one_index(f)
def create_one_index(filename):
if(filename[-1]!="l"): return
template = file("noinfo/areapage_skeletons/"+filename).read()
try:
destination = re.search(r'<destination\s*dest="([^"]*)"\s*/>', template, re.IGNORECASE).group(1)
except:
print "Error on: ", filename
return
outfile = file(destination, "w")
template = re.sub(r'(?i)<head>', '<head>' + (WARNING_MESSAGE % filename), template)
outfile.write(re.sub(r'(?i)<areatable\s*areacode="([^"]*)"\s*/>', formatted_table, template))
# re.sub doesn't support re.IGNORECASE, so use (?i) escape code
def formatted_table(area_matchobj):
area = area_matchobj.group(1)
thisarea_caves = filter(lambda u: inarea(u, area), caves)
t = TABLE_PREAMBLE
for cave in thisarea_caves:
args = {"number" : number(cave),
"lcnumber" : number(cave).lower(),
"url" : "../" + cave["Autogen file"],
"name" : cave["Name"] or cave["Unofficial Name"] or "?"}
t = t + (TABLE_LINE % args)
return t + TABLE_POSTAMBLE
def number(cave):
return cave["Kataster Number"] or cave["Unofficial number"]
def chomp(s):
if(s[-1] == "\n"): return s[:-1]
else: return s
def inarea(cave, area):
return re.match(area+r'[a-z]*', cave["Area"])
main()