Wikiproyecto:La Rioja/datos municipales/obtener plantilla nueva

#! /usr/bin/env python
# -*- coding: utf-8 -*-

#ATENCIÓN!! Para la ejecución de este script es necesario el paquete python-pysqlite2 que se encuentra en 
# repositorios debian y ubuntu. Ha sido probado solo en Linux.

# infobox.py: Crea infoboxes para las Población que cumplan un where pasado como parámetro para ser incluidos en los artículos de la wikipedia
# versión:	0.6.2
# autor:	BigSus
# modificaciones: Jynus
# fecha:	21 oct 2006
# Este script viene sin ningún tipo de garantías
# 
#	Copyright (C) 2006 BigSus
# 
#	 This program is free software; you can redistribute it and/or modify
#	 it under the terms of the GNU General Public License as published by
#	 the Free Software Foundation; either version 2 of the License, or
#	 (at your option) any later version.
# 
#	 This program is distributed in the hope that it will be useful,
#	 but WITHOUT ANY WARRANTY; without even the implied warranty of
#	 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	 GNU General Public License for more details.
# 
#	 You should have received a copy of the GNU General Public License
#	 along with this program; if not, write to the Free Software
#	 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

import os
import codecs
import sys
import datetime

from pysqlite2 import dbapi2 as sqlite

def prepararTablas():
	cursor = con.cursor()
	#Creación de tabla municipios
	cursor.execute('CREATE TABLE municipios (id INTEGER PRIMARY KEY, EsMunicipio VARCHAR(2), Población VARCHAR(50), Municipio VARCHAR(50), PartidoJudicial VARCHAR(50), ZonaSalud VARCHAR(50), Comarca VARCHAR(50), Región VARCHAR(50), Gentilicio VARCHAR(50), Fundación VARCHAR(50), Patrón VARCHAR(75), Patrona VARCHAR(75), Superficie VARCHAR(10), NucleosPoblación INTEGER, AldeasDeMunicipio VARCHAR(150), Latitud VARCHAR(15), Longitud VARCHAR(15), Altitud INTEGER, CodigoPostal VARCHAR(50), DistanciaALogroño INTEGER, DistanciaACabecera INTEGER, Alcalde VARCHAR(70), Partido VARCHAR(50), Hermanado VARCHAR(100), Web VARCHAR(50), Poblac1900 INTEGER, Poblac1910 INTEGER, Poblac1920 INTEGER, Poblac1930 INTEGER, Poblac1940 INTEGER, Poblac1950 INTEGER, Poblac1960 INTEGER, Poblac1970 INTEGER, Poblac1981 INTEGER, PobOLD1991 INTEGER, Poblac1986 INTEGER, Poblac1987 INTEGER, Poblac1988 INTEGER, Poblac1989 INTEGER, Poblac1990 INTEGER, Poblac1991 INTEGER, Poblac1992 INTEGER, Poblac1993 INTEGER, Poblac1994 INTEGER, Poblac1995 INTEGER, Poblac1996 INTEGER, Poblac1998 INTEGER, Poblac1999 INTEGER, Poblac2000 INTEGER, Poblac2001 INTEGER, Poblac2002 INTEGER, Poblac2003 INTEGER, Poblac2004 INTEGER, Poblac2005 INTEGER, Densidad2005 VARCHAR(10), Presupuesto2005 VARCHAR(15), WikiName VARCHAR(70))')
	#Inserción de datos de municipios obtenidos de wikipedia
	insertarMunicipios()
	cursor.lastrowid
	con.commit()	

#Obtención de datos municipales y mapa base de La Rioja
def descargarDatos():
	os.system("wget -q -O datos.xml http://es.wikipedia.org/wiki/Wikiproyecto:La_Rioja/datos_municipales")

def insertarMunicipios():
	cursor = con.cursor()
	estamos = 0
	#Abriendo fichero de datos municipales
	for linea in open("datos.xml"):
		if linea=="<"+"pre>\n":
			estamos = 1 #Buscando comienzo de datos municipales
		elif linea=="<"+"/pre></div>\n":
			estamos = 0 #Encontrado fin de datos municipales
		elif estamos == 1: 
			estamos = 2
		elif estamos == 2: #Saltar las dos primeras lineas, es una ñapa, pero hasta encontrar una solución mejor ...
			estamos = 3
		elif estamos == 3:
			#Preparando la linea para insertar en la base de datos
			linea = linea.replace(";;",";null;").replace(";;",";null;")
			linea = linea.replace(";\n",";null\n")
			linea = linea.replace("\n","")
			linea = linea.replace(',',".")
			cursor.execute('INSERT INTO MUNICIPIOS VALUES (' + linea.replace(";",",") + ')')


def crearInfobox(wherecursor):
	cursor = con.cursor()
	cursor.execute('SELECT id, EsMunicipio, Población, Municipio, Región, Comarca, CodigoPostal, Latitud, Longitud, Superficie, Altitud, DistanciaACabecera, DistanciaALogroño, Poblac2005, Fundación, Gentilicio, Densidad2005, Alcalde, Partido, Hermanado, Patrón, Patrona, Web, Presupuesto2005, AldeasDeMunicipio, WikiName FROM municipios WHERE ' + wherecursor)
			
	#Creando lineas de los municipios que cumplan la condición
	for (id, EsMunicipio, Poblacion, Municipio, Region, Comarca, CodigoPostal, Latitud, Longitud, Superficie, Altitud, DistanciaACabecera, DistanciaALogrono, Poblac2005, Fundacion, Gentilicio, Densidad2005, Alcalde, Partido, Hermanado, Patron, Patrona, Web, Presupuesto2005, AldeasDeMunicipio, WikiName) in cursor:
		print "{{Infobox ciudad España"
		print "| nombre = %s" % (Poblacion.encode( tipoencode ))
		print "| bandera ="
		print "| escudo ="
		print "| imagen = [[Imagen:%s - La Rioja (Spain) - Municipality Map.svg|220px]]" % (Municipio.encode( tipoencode ))
		print "| cod_provincia = 26"
		print "| región = [[%s]]" % (Region.encode( tipoencode ))
		if Comarca.encode( tipoencode )=="Camero Nuevo" or Comarca.encode( tipoencode )=="Camero Viejo":
			print "| comarca = [[%s]]" % (Comarca.encode( tipoencode ))
		elif Comarca.encode( tipoencode )=="Cervera del Río Alhama":
			print "| comarca = [[Comarca de Cervera|Cervera]]"
		else:
			print "| comarca = [[Comarca de %s|%s]]" % (Comarca.encode( tipoencode ),Comarca.encode( tipoencode ))
		if EsMunicipio == "NO":
			print "| municipio = [[%s]]" % (Municipio.encode( tipoencode ))
		print "| cp = %s" % (CodigoPostal)
		if Latitud != None and Longitud != None:
			lat = Latitud.split(".")
			if(len(lat) < 2):
				lat.append('0')
			lon = Longitud.split(".")
			if(len(lon) < 2):
				lon.append('0')
			print "| coor = {{coor dms|%i|%i|0|N|%i|%i|0|O}}" % (int(lat[0]),int(int(lat[1])*0.60 + 0.5),-int(lon[0]),int(int(lon[1])*0.60 + 0.5))
		else:
			print "| coor = "

		if Superficie != None:
			print "| superficie = %s" % (Superficie.replace(".", ","))
		else:
			print "| superficie = "

		if Altitud != None:
			print "| altitud = %i" % (Altitud)
		else:
			print "| altitud = "

		if Poblacion.encode( tipoencode )=="Logroño":
			print "| distancia = 333"
			print "| referencia = [[Madrid]]"
		elif DistanciaALogrono != None:
			print "| distancia = %i" % (DistanciaALogrono)
			print "| referencia = [[Logroño]]"

		if EsMunicipio == "SI" and \
			Poblacion.encode( tipoencode ) != "Cervera del Río Alhama" and \
			Poblacion.encode( tipoencode ) != "Torrecilla en Cameros" and \
			Comarca.encode( tipoencode ) != "Logroño" and \
			Poblacion.encode( tipoencode ) != Comarca.encode( tipoencode ) and \
			DistanciaACabecera != None:
			print "| distancia2 = %i" % (DistanciaACabecera)
			if Comarca.encode( tipoencode ) == "Camero Nuevo" or Comarca.encode( tipoencode ) == "Camero Viejo":
				print "| referencia2 = [[Torrecilla en Cameros]]"
			else:
				print "| referencia2 = [[%s]]" % (Comarca.encode( tipoencode ))

		if Fundacion != None:
			print "| fundación = %s" % (Fundacion.encode( tipoencode ))
		else:
			print "| fundación = "

		if Poblac2005 != None:
			print "| población = %i" % (Poblac2005)
			print "| ine_año = 2005"
			print "| densidad = %s" % (Densidad2005.replace(".", ","))
		else:
			print "| población = "
			print "| ine_año = "
			print "| densidad = "

		if EsMunicipio == "SI" and AldeasDeMunicipio != None:
			print "| núcleos = %s" % (separarEnlaces(AldeasDeMunicipio.replace('.',",").encode( tipoencode )))

		if Gentilicio != None:
			print "| gentilicio = %s" % (Gentilicio.encode( tipoencode ))
		else:
			print "| gentilicio = "

		if Partido=="PSOE":
			Partido = "[[Partido Socialista Obrero Español|PSOE]]"
		elif Partido=="PP":
			Partido = "[[Partido Popular|PP]]"
		elif Partido=="PR":
			Partido = "[[Partido Riojano|PR]]"
		elif Partido=="IND.":
			Partido = "Independiente"

		if EsMunicipio == "SI" and Alcalde != None and Partido != None:
			print "| alcalde = %s (%s)" % (Alcalde.encode( tipoencode ),Partido)
			print "| alcalde_año = 2003"

		if EsMunicipio == "SI" and Presupuesto2005 != None:
			print "| presupuesto = %s " % (Presupuesto2005.encode( tipoencode ))
			print "| presupuesto_año = 2005"

		if Hermanado != None:
			print "| hermandad = %s" % (Hermanado.encode( tipoencode ).replace(".","<br />"))
		else:
			print "| hermandad = "

		if Patron != None:
			print "| patrón = %s" % (Patron.encode( tipoencode ))
		else:
			print "| patrón = "
		if Patrona != None:
			print "| patrona = %s" % (Patrona.encode( tipoencode ))
		else:
			print "| patrona = "

		if Web != None:
			print "| web = [%s Ayuntamiento]" % (Web)
		else:
			print "| web = "

		print "}}"
		
		print Cuerpo(Poblacion.encode( tipoencode ),Municipio.encode( tipoencode ))

def Cuerpo(nombrePoblacion,nombreMunicipio):
	if nombrePoblacion==nombreMunicipio:
		texto = "'''%s''' es un municipio de la comunidad autónoma de [[La Rioja (España)|La Rioja]] ([[España]]).\n\n" +\
			"== Historia ==\n" +\
			"== Demografía ==\n" +\
			"{{Demografía/%s - La Rioja - España (Siglo XX)}}\n\n" +\
			"== Comunicaciones ==\n" +\
			"== Lugares de interés ==\n" +\
			"=== Edificios y monumentos ===\n" +\
			"=== Museos ===\n" +\
			"=== Parques y Jardines ===\n" +\
			"=== Bodegas de Prestigio ===\n" +\
			"=== Otros lugares de interés ===\n" +\
			"== Gastronomía y Hostelería ==\n" +\
			"== Deporte ==\n" +\
			"== Fiestas Locales ==\n" +\
			"== Personajes ilustres ==\n" +\
			"== Véase también ==\n" +\
			"== Enlaces externos ==\n\n" +\
			"{{miniesbozo de|geografía de La Rioja (España)}}\n" +\
			"[[Categoría:Localidades de La Rioja (España)]]\n\n" +\
			"[[eu:%s]]\n" +\
			"[[it:%s]]\n" +\
			"[[pt:%s]]".encode( tipoencode )
		texto = texto % (nombrePoblacion,nombrePoblacion,nombrePoblacion,nombrePoblacion,nombrePoblacion)
	else:
		texto = "'''%s''' es una población perteneciente al municipio de [[%s]] en la comunidad autónoma de [[La Rioja (España)|La Rioja]] ([[España]]).\n\n" +\
			"{{miniesbozo de|geografía de La Rioja (España)}}\n" +\
			"[[Categoría:Localidades de La Rioja (España)]]"
		texto = texto % (nombrePoblacion,nombreMunicipio)
	return texto

def separarEnlaces(cadena):
	texto = ""
	for x in cadena.split(","):
		if texto!="":
			texto += ", "
		texto += "[[" + x.strip() + "]]"

	return texto

#Comienzo del programa
try:
	where = sys.argv[1]
except IndexError:
	print "Debe indicar una sentencia sql para preparar el mapa"
	print 'Por ejemplo "Población=\'Haro\'"'
	raise SystemExit("Número de parámetros incorrectos")

tipoencode = "utf-8"		#Este es el formato ideal, pero la consola de XP no lo soporta
#tipoencode = "iso-8859-1"	#Para sistemas que no soporten utf-8 correctamente, como windows

#Creación de base de datos temporal
con = sqlite.connect(":memory:")

descargarDatos()
prepararTablas()
crearInfobox(where)