De Wiki do Arch Linux Brasil
#!/usr/bin/env python
# coding: utf-8
#### Baixa um arquivo texto com cordenadas de um mapa e imprime na tela
#### o código kml (xml usado no googlemaps)
## Autor: Audren Cezar
## E-mail: audrencezar arroba gmail ponto com
## Última alteração: 2008-07-05
## Depende de:
## python
from string import Template
import re
from urllib2 import urlopen
class Text2Kml:
#<latitude> <longitude> <nome> # <cidade>, <estado>
#<latitude> <longitude> [[User:<nome_de_usuario_no_wiki>|<nome>]] # <cidade>, <estado>
regex = re.compile(r'\* (?P<lat>-?\d+\.\d+) (?P<lon>-?\d+\.\d+) (\")?(\[\[User\:(?P<wikiusername>[^\|]+)\|)?(?P<name>.+?)(\]\])?(\"?) # +(?P<description>.*)')
header_template = Template("""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
<name>${mapname}</name>
<description><![CDATA[${mapdescription}]]]></description>
<Style id="style1">
${style}
</Style>
""")
placemark_template = Template(""" <Placemark>
<name>${name}</name>
<description><![CDATA[<div dir="ltr">${description}</div>]]></description>
<styleUrl>#style1</styleUrl>
<Point>
<coordinates>${lon},${lat},0.000000</coordinates>
</Point>
</Placemark>""")
footer = """</Document>
</kml>
"""
wikilink_template = Template('; <a href="${wikiurl}${wikiusername}">${name}</a>')
def __init__(self, url, mapname, mapdescription, wikiurl=None, style=""):
self.url = url
self.wikiurl = wikiurl
self.mapname = mapname
self.mapdescription = mapdescription
self.style = style
def parse(self):
print(self.header_template.substitute({
'mapname': self.mapname,
'mapdescription': self.mapdescription,
'style': self.style
}))
file = urlopen(self.url)
for line in file:
res = self.regex.match(line)
if res:
d = res.groupdict()
if self.wikiurl and d['wikiusername']:
d['wikiurl'] = self.wikiurl
d['description'] += self.wikilink_template.substitute(d)
print(self.placemark_template.substitute(d))
file.close()
def parsey(self):
yield self.header_template.substitute({
'mapname': self.mapname,
'mapdescription': self.mapdescription,
'style': self.style
})
file = urlopen(self.url)
for line in file:
res = self.regex.match(line)
if res:
d = res.groupdict()
if self.wikiurl and d['wikiusername']:
d['wikiurl'] = self.wikiurl
d['description'] += self.wikilink_template.substitute(d)
yield self.placemark_template.substitute(d)
file.close()
yield self.footer
if __name__ == "__main__":
style = """<IconStyle>
<Icon>
<href>http://img379.imageshack.us/img379/8628/arch2jb7.png</href>
</Icon>
</IconStyle>"""
parser = Text2Kml(
"http://wiki.archlinux-br.org/Especial:Exportar/ArchersNoBrasil",
"ArchersNoBrasil",
"Usuários Arch Linux no Brasil",
"http://wiki.archlinux-br.org/Usuário:",
style)
#parser.parse()
# uso .xml porque alguns servidores não reconhecem a extensão .kml
wfile = open("ArchersNoBrasil.kml.xml", 'w')
for p in parser.parsey():
wfile.write(p)
wfile.close()