Usuari:VriuBot/referències

#/usr/bin/python2.5
#-*- coding: utf-8 -*-

# Traducció de la plantilla cite book a ref llibre
import codecs, re
import wikipedia, pagegenerators

def corrpara (match):
	text = match.group('aixo')
	# correcció típica paràmetre id
	noutext = re.sub("(?i)id( *= *)ISBN",r"isbn\1", text)
	noutext = re.sub("(?i)isbn( *= *)ISBN",r"isbn\1", noutext)
	parametres = text.split("|")
	for parametre in parametres:
		if not "=" in parametre:
			if parametre.strip() == "": # està buit, amb | |
				noutext = re.sub("\|\s*\|", "|", noutext)
			elif not "]]" in parametre:  # és un enllaç conduït, no un paràmetre
				log.write(u"* %s: %s\n" %(pagina.title(asLink=True), parametre))
		else:
			titolpara = parametre.split("=")[0].strip()
			valor = parametre.split("=",1)[1].strip()
			if titolpara.lower() != titolpara: # tots els noms de paràmetre amb minúscula
				titolparanou = titolpara.lower()
				noutext = re.sub(ur"%s( *=)" % titolpara, r"%s\1" % titolparanou, noutext)
				parametre = re.sub(titolpara, titolparanou, parametre)
				titolpara = titolparanou
			if titolpara in paradict: # traducció del diccionari
				titolparanou = paradict.get(titolpara)
				noutext = re.sub(u"%s( *=)" % titolpara, r"%s\1" % titolparanou, noutext) # pendent: date->data canvia també accessdate->accessdata
				parametre = re.sub(titolpara, titolparanou, parametre)
				titolpara = titolparanou
			if (valor == "" and not titolpara in paramin) or titolpara in paranot: # paràmetres buits opcionals o no tractats: a eliminar
				if parametre == parametres[0]:
					noutext = re.sub(u"%s\|" % parametre, "", noutext)
				else:
					noutext = re.sub(u"\|%s" % parametre, "", noutext)
			elif titolpara in ("revista", u"publicació", "issn", "journal", "obra"): # no és un llibre
				return r"{{citar ref%s%s%s}}" % (match.group('pre'), noutext)
			elif titolpara == "llengua" and valor.lower() != valor: # nom de llengua en minúscula
				noutext = re.sub(u"llengua( *= *)%s" % valor, r"llengua\1%s" % valor.lower(), noutext)
			elif titolpara == u"títol" and valor.startswith("''") and valor.endswith("''"): # títol sense cursiva ni negreta
				noutext = re.sub(u"títol( *= *)'+(.*?)'+", ur"títol\1\2", noutext)
			elif not titolpara in para and not titolpara in paranot: # paràmetre desconegut
				log.write(u"* %s: %s\n" %(pagina.title(asLink=True), titolpara))
	if noutext != text:
		return r"{{ref llibre%s%s}}" % (match.group('pre'), noutext)
	return r"{{%s%s%s}}" % (match.group('nom'), match.group('pre'), text)
	
def main():
	tots = pagegenerators.ReferringPageGenerator(wikipedia.Page(lloc, titol), onlyTemplateInclusion=True)
	articles = pagegenerators.NamespaceFilterPageGenerator(tots, [0])
	llista = pagegenerators.PreloadingGenerator(articles, pageNumber = 50)
	pags=vistes=0
	global pagina
	for pagina in llista:
		vistes+=1
		try:
			text = pagina.get(get_redirect=True)
			noutext = re.sub(u"(?s)\{\{(?P<nom>[Cc]ite[_ ]book)(?P<pre>\s*\|)(?P<aixo>.*?)\}\}", corrpara, text)
			if noutext != text:
				pags+=1
				if edit: pagina.put(noutext, resum)
				if not edit: wikipedia.output(pagina.aslink())
				if informa: wikipedia.showDiff(text, noutext)
		except wikipedia.IsRedirectPage:
			log.write(u"* %s: és una redirecció\n" % pagina.title(asLink=True))
		except wikipedia.NoPage:
			log.write(u"* %s: pàgina no trobada\n" % pagina.title(asLink=True))
		except wikipedia.EditConflict:
			log.write(u"* %s: no fet, conflicte d'edició\n" % pagina.title(asLink=True))
		except wikipedia.LockedPage:
			log.write(u"* %s: està protegida.\r\n" % pagina.title(asLink=True))
		except KeyboardInterrupt:
			log.close()
			exit()
		log.flush()
	log.close()
	wikipedia.output(
		u"S'han fet canvis en %i pàgines de %i llegides.\nEl darrer article analitzat ha estat [[%s]]."
		% (pags, vistes, pagina.title(asLink=True))
	)

if __name__ == "__main__":
	# Variables
	# Paràmetres acceptats a ref llibre
	para = [
		"nom","cognom",u"enllaçautor","autor","coautors","editor","altres",
		"nom2","cognom2",u"enllaçautor2","nom3","cognom3",u"enllaçautor3",
		"url",u"urlcapítol","urlarxiu","dataarxiu","anyarxiu","mesarxiu","consulta",u"anyaccés",u"mesaccés",
		u"títol",u"capítol","editorial","lloc","data","any","mes",
		u"pàgina",u"pàgines",u"col·lecció","volum",u"edició","llengua","idioma","format",
		"doi","id","isbn","oclc","lccn",u"citació","cita","ref"
	]
	
	# Paràmetres traduïts de cite book a ref llibe 
	paradict = {
		"author":"autor", "author1":u"autor", "authorlink":u"enllaçautor", "authorlink1":u"enllaçautor",
		"coauthors":"coautors", "coauthor":"coautors",
		"first":"nom", "first1":"nom", "given":"nom", "last1":"cognom", "last":"cognom", "surname":"cognom",
		"first2":"nom2", "given2":"nom2", "last2":"cognom2", "surname2":"cognom2", "authorlink2":u"enllaçautor2",
		"first3":"nom3", "given3":"nom3", "last3":"cognom3", "surname3":"cognom3", "authorlink3":u"enllaçautor3",
		"first4":"nom4", "given4":"nom4", "last4":"cognom4", "surname4":"cognom4",
		"first5":"nom5", "given5":"nom5", "last5":"cognom5", "surname5":"cognom5",
		"first6":"nom6", "given6":"nom6", "last6":"cognom6", "surname6":"cognom6",
		"coauthors":"coautors", "others":"altres",
		"origdate":"dataarxiu", "origyear":"anyarxiu", "origmonth":"mesarxiu",
		"chapter":u"capítol", "chapterurl":u"urlcapítol", "title":u"títol",
		"volume":"volum", "edition":u"edició", "series":u"col·lecció", "serie":u"col·lecció",
		"language":"llengua", "publisher":"editorial", "location":"lloc", "place":"lloc",
		"date":"data", "year":"any", "month":"mes", "page":u"pàgina", "pages":u"pàgines",
		"accessdate":"consulta", "accessyear":u"anyaccés", "accessmonth":u"mesaccés",
		"archiveurl":"url", "archivedate":u"dataarxiu",
		"quote":u"citació"
	}
	
	# Paràmetres mínims sense els opcionals
	paramin = ["nom","cognom",u"títol","editorial","lloc","data",u"pàgines","isbn","ref"]
	# Paràmetres a eliminar, encara que tinguin contingut
	paranot = [
		"editor1-link","trans_title","type","at","trans_chapter","bibcode","laysummary","laydate",
		"author-mask","author-name-separator","author-separator","display-authors","separator","postscript",
		"lastauthoramp","origdate","origyear","nopp","editor2-first","editor2-last","editor3-first",
		"editor3-last","editor4-first","editor4-last","editor5-first","editor5-last","editor6-first",
		"editor6-last","editor7-first","editor7-last","editor8-first","editor8-last"
	]
	resum   = u"Traduïnt plantilla cite book a ref llibre"
	edit    = True
	informa = True
	titol   = u"Plantilla:Cite book"
	lloc    = wikipedia.getSite("ca", "wikipedia")
	log     = codecs.open("refllibre.txt", "w", "utf-8")
		
	try:
		main()
	finally:
		wikipedia.stopme()