Utente:Wisbot/asteroidi.py: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
Wiso (discussione | contributi)
Nuova pagina: <source lang=python> """ Modifiche asteroidi -first:X Primo asteroide su cui agisce, poi segue l'ordine della lista ...
 
m typo da raffreddore
 
(5 versioni intermedie di 2 utenti non mostrate)
Riga 1:
<source lang=python>
# -*- coding: utf-8 -*-
 
"""
Modifiche asteroidi
Riga 13:
argomento non nullo
-valore:V Agisce solo sugli astoroidiasteroidi che hanno un certo
argomento con un certo valore (usare con
l'opzione -argomento)
Riga 19:
"""
#
# [[Utente:Wiso]] 20072008
#
# Distributed under the terms of the GPL licence
Riga 109:
for row in rows:
self.writerow(row)
 
def text2regex(text):
text = re.escape(text)
# maiuscole / minuscole come iniziale
if text[0].isalpha():
text = '[' + text.upper()[0] + text.lower()[0] + ']' + text[1:]
return text
 
def name2regex(name):
name = re.escape(name)
# maiuscole / minuscole come iniziale
if name[0].isalpha():
name = '[' + name.upper()[0] + name.lower()[0] + ']' + name[1:]
# spazio -> [ _]
name = name.replace('\ ','[ _]').replace('\_','[ _]')
return name
class botAsteroidi:
def __init__(self, gen, acceptall = False):
self.gen = gen
self.site = wikipedia.getSite()
self.acceptall = acceptall
 
def campo_pieno(self,campo,text):
Riga 146 ⟶ 156:
return newtext
 
def inserisci_da_non_vuotoaggiungi_da_non_vuoto(self,text,campo,argomento,separator=u''):
regex = re.compile(u'\| ?' + name2regex(campo) + ' ?= ?(.+)')
newtextmatch = regex.subsearch('|' + campo + ' = ' + argomento,text)
return newtext if not match:
wikipedia.output(u'\03{lightred}ERROR 20: IL CAMPO %s DOVEVA ESSERE GIÀ COMPILATO, MA NON LO È\03{default}' %campo)
return text
vecchio = match.group(1)
regexNuovo = re.compile(name2regex(argomento.strip()),re.IGNORECASE)
match2 = regexNuovo.search(vecchio)
if match2:
wikipedia.output(u'Il campo %s era correttamente compilato' % campo)
return text
else:
argomentoNuovo = argomento + separator + vecchio
wikipedia.output(u'\03{lightyellow}WARNING 10: IL CAMPO %s ERA GIÀ COMPILATO. SOSTITUZIONE "%s" -> "%s"' %(campo,vecchio,argomentoNuovo))
newtext = regex.sub('|' + campo + ' = ' + argomentoNuovo,text)
return newtext
 
def sostituisci_da_non_vuoto(self,text,campo,argomento):
regex = re.compile(u'\| ?' + name2regex(campo) + ' ?= ?(.+)')
match = regex.search(text)
if not match:
wikipedia.output(u'\03{lightred}ERROR 110: IL CAMPO %s DOVEVA ESSERE GIÀ COMPILATO, MA NON LO È\03{default}' %campo)
return text
vecchio = match.group(1)
regexNuovo = re.compile(name2regex(argomento.strip()),re.IGNORECASE)
match2 = regexNuovo.search(vecchio)
if match2:
wikipedia.output(u'Il campo %s era correttamente compilato' % campo)
return text
else:
argomentoNuovo = argomento
wikipedia.output(u'\03{lightyellow}WARNING 20: IL CAMPO %s ERA GIÀ COMPILATO. SOSTITUZIONE "%s" -> "%s"' %(campo,vecchio,argomentoNuovo))
newtext = regex.sub('|' + campo + ' = ' + argomentoNuovo,text)
return newtext
def campo(self,text,campo,valore,aggiungi=False,separator=''):
"""
compila un campo con un certo valore nel template. Se aggiungi = True
aggiunge, se False sostituisce. Fa vari controlli e riporta
avvertimenti. Il campo separarator serve per separare i valori
nel caso vengano aggiunti
"""
if not self.campo_esiste(campo,text):
wikipedia.output(u'Il campo %s non esisteva, lo inserisco' % campo)
text = self.inserisci_da_zero(text,campo,valore)
pass
else:
valore_vecchio = self.campo_pieno(campo,text)
if valore_vecchio:
wikipedia.output(u'Il campo %s era già compilato. Vecchio: %s' %(campo,valore_vecchio))
if valore_vecchio.lower() != valore.lower():
wikipedia.output(u'Loif sostistuisco con %s' %valore)aggiungi:
text = self wikipedia.inserisci_da_non_vuotooutput(text,campo,u'Aggiungo %s' %valore)
text = self.aggiungi_da_non_vuoto(text,campo,valore,separator)
else:
wikipedia.output(u'Sostituisco con %s' %valore)
text = self.sostituisci_da_non_vuoto(text,campo,valore)
else:
wikipedia.output(u'Il valore %s nel campo %s già inserito era corretto' %(valore,campo))
else:
wikipedia.output(u'Il campo %s esisteva già vuoto' %campo)
Riga 171 ⟶ 223:
 
def aggiungi_cat(self,text,cat):
"""
regex = re.compile('\[\[[Cc]ategoria ?: ?Asteroidi del sistema solare(.*?)\]\]')
Aggiunge una categoria. Se la categoria è già presente non fa nulla. La
text = regex.sub('\\0\n[[Categoria:%s|\\1]] %cat',text)
categoria viene aggiunta dopo una categoria già presente che inizia
con Asteroid. Viene restituito il testo modificato.
"""
# controllo che la categoria non sia già presente
regex = re.compile(u'\[\[[Cc]ategoria ?: ?%s' %name2regex(cat))
if regex.search(text):
wikipedia.output(u'\03{lightyellow}La categoria %s era già presente\03{default}' %cat)
return text
# faccio l'aggiunta dopo una categoria già presente
regex = re.compile('(\[\[[Cc]ategoria ?: ?[Aa]steroid.*?\|(.*?)\]\])')
(text,n) = regex.subn(u'\\1\n[[Categoria:%s|\\2]]' %cat,text,1)
# controllo che sia stata aggiunta
if n==0:
wikipedia.output(u'\03{lightred}ERROR 31: NON RIESCO AD INSERIRE LA CATEGORIA: %s' %cat)
return text
 
def aggiungi_testo(self,text,new):
"""
Inserisce la stringa new nel testo text dopo la prima frase. La prima
frase è quella dopo il primo template, che contiene il carattere 'è'
e che finisce con un '.'. Se la stringa new era già presente nel testo
non fa nulla. Resistuisce il testo modificato.
"""
# controlla che la stringa non sia già presente
regex = re.compile(text2regex(new))
if regex.search(text):
wikipedia.output(u'\03{lightyellow}La stringa "%s" era già presente nel testo' %new)
return text
# aggiunta
regex = re.compile(u'(}}.+?è.+?)\. ?',re.DOTALL)
(text,n) = regex.subn(u'\\1%s. ' %new,text,1)
# controlla che la sostituzione sia avvenuta
if n==0:
wikipedia.output(u'\03{lightred}ERRERROR 40: NON RIESCO AD INSERIRE LA STRINGA %s ALLA FINE DELLA PRIMA FRASE\03{default}' %new)
return text
Riga 189 ⟶ 268:
if new in text:
wikipedia.output(u'\03{lightyellow}Il testo "%s" era già inserito\03{default}' %new)
return text
else:
wikipedia.output(u'\03{lightred}ERRERROR 50 NON RIESCO AD INSERIRE IL TESTO %s\03{default}' %new)
return text
return newtext
 
def nome_alternativo(self,text,nome):
campo = u'designazioni_alternative'
return self.campo(text,campo,nome,aggiungi=True,separator=u', ')
 
def albedo(self,text,al):
Riga 207 ⟶ 288:
 
def diam(self,text,diam):
campo = u'dimensionidiametro_med'
diam += ' km'
text = self.aggiungi_testo(text,' del diametro medio di circa %s' %diam)
Riga 224 ⟶ 305:
 
def spettro(self,text,sp):
campo = u'classe_spettrale'
text = self.campo(text,campo,sp)
sp = sp.rstrip(':')
text = self.aggiungi_cat(text,'Asteroidi di tipo %s' %sp)
return text
Riga 251 ⟶ 333:
elif orbit == 'ATE':
new_template = u'[[asteroide Aten]]'
new_descrizione = u'è un [[asteroide NEAR]]'
elif orbit == 'CEN':
new_template = u'[[Centauro (astronomia)|asteroide centauro]]'
Riga 264 ⟶ 346:
text = self.aggiungi_cat(text,cat)
else:
wikipedia.output(u'\03{lightred}ERRERROR 60: Parametro orbit non valido: %s\03{default}' %orbit)
return text
text = self.campo(text,'categoria',new_template,aggiungi=True,separator=u', ')
text = self.sostituisci_testo(text,regex_descrizione,new_descrizione)
if newcat:
Riga 275 ⟶ 357:
 
def fix_category(self,text):
return text.replace('Category','Categoria')
 
def funzioneOrdine(self,x):
ordine = [
u'tipo',
u'soprattitolo',
u'lettera_stella',
u'nome_stella',
u'id_stella',
u'nome',
u'sottotitolo',
u'pianeta_madre',
u'numero_satellite',
u'stella_madre',
u'distanza_anniluce',
u'sigla_costellazione',
u'immagine',
u'dimensione_immagine',
u'didascalia',
u'scoperta_autore',
u'scoperta_autori',
u'data',
u'categoria',
u'famiglia',
u'ar',
u'declinaz',
u'lat_galattica',
u'long_galattica',
u'classe_spettrale',
u'tipo_variabile',
u'periodo_variabile',
u'designazioni_alternative',
u'designazioni_alternative_stellari',
u'redshift',
u'epoca',
u'semiasse_maggiore',
u'circonferenza_orbitale',
u'periastro',
u'afastro',
u'eccentricità',
u'periodo_orbitale',
u'periodo_sinodico',
u'velocità_min',
u'velocità_media',
u'velocità_max',
u'inclinazione_orbita',
u'inclinazione_orbita_su_eclittica',
u'inclinazione_orbita_su_eq',
u'inclinazione_orbita_su_orbita',
u'inclinazione_orbita_su_eq_sole',
u'inclinazione_orbita_su_p_laplace',
u'nodo_ascendente',
u'argomento_perielio',
u'anomalia_media',
u'ultimo_perielio',
u'prossimo_perielio',
u'pianeti',
u'satelliti',
u'anelli',
u'dimensioni',
u'raggio',
u'diametro_eq',
u'diametro_pol',
u'diametro_med',
u'diametro_sole',
u'schiacciamento',
u'superficie',
u'volume',
u'massa',
u'massa_sole',
u'densità',
u'accel_gravità',
u'velocitàdifuga',
u'periodo_rotaz',
u'periodo_rotaz_1_descrizione',
u'periodo_rotaz_1',
u'periodo_rotaz_2_descrizione',
u'periodo_rotaz_2',
u'periodo_rotaz_3_descrizione',
u'periodo_rotaz_3',
u'periodo_rotaz_4_descrizione',
u'periodo_rotaz_4',
u'velocità_rotaz',
u'velocità_rotaz_note',
u'inclinazione_asse',
u'inclinazione_asse_su_eclittica',
u'inclinazione_asse_su_piano_galattico',
u'ascensionerettapolonord',
u'declinazione',
u'temp_min',
u'temp_med',
u'temp_max',
u'temp_sommitànubi_min',
u'temp_sommitànubi_med',
u'temp_sommitànubi_max',
u'temp_corona',
u'temp_nucleo',
u'luminosità',
u'luminosità_sole',
u'radianza',
u'indice_di_colore',
u'metallicità',
u'pressione_atmosferica',
u'albedo',
u'età',
u'magn_app',
u'magn_app_min',
u'magn_app_med',
u'magn_app_max',
u'magn_app_min_corpomadre',
u'magn_app_med_corpomadre',
u'magn_app_max_corpomadre',
u'magn_ass',
u'dim_app_min',
u'dim_app_med',
u'dim_app_max',
u'dim_app_min_corpomadre',
u'dim_app_med_corpomadre',
u'dim_app_max_corpomadre',
u'parallasse',
u'moto_proprio',
u'velocità_radiale']
try:
return ordine.index(x[0].strip().lower())
except ValueError:
wikipedia.output(u'ERROR 00 \03{lightred} Non trovo nella lista degli argomenti possibili "%s"\03{default}' % x)
return 0
 
def templatesWithParams(self,thistxt):
# remove commented-out stuff etc.
thistxt = wikipedia.removeDisabledParts(thistxt)
 
# marker for | in wikilink
marker = '@@'
while marker in thistxt:
marker += '@'
result = []
count = 0
Rtemplate = re.compile(r'{{([Tt]emplate:)?([Cc]orpo[ _]celeste).*?(\|(?P<params>[^{]+?))?}}',re.DOTALL)
RMarker = re.compile(r'(\[\[.+?)\|(.+?\]\])')
m = Rtemplate.search(thistxt)
if not m:
wikipedia.output('\03{lightred}ERROR 70: NON RIESCO A TROVARE IL TEMPLATE\03{default}')
return []
# Parameters
paramString = m.group('params')
params = []
if paramString:
paramString = RMarker.sub('\\1%s\\2' % marker, paramString)
 
# Parse string
markedParams = paramString.split('|')
for param in markedParams:
param = param.replace(marker,u'|')
params.append(param)
return params
 
def fixTemplate(self,text):
regex = re.compile(u'\|}}',re.DOTALL)
text = regex.sub('}}',text)
return text
 
def ordinaTemplate(self,text,listaCampi):
import operator
listaOrdinata = None
for i in range(0,len(listaCampi)):
if not '=' in listaCampi[i]:
wikipedia.output('\03{lightred}ERROR 83: IL CAMPO "%s" NON CONTIENE "=", salto ordinamento\03{default}' %listaCampi[i])
return text
listaCampi[i] = listaCampi[i].split('=')
listaCampi[i][0] = listaCampi[i][0].strip()
listaCampi[i][1] = listaCampi[i][1].strip()
 
listaOrdinata = sorted(listaCampi, key=self.funzioneOrdine)
if not listaOrdinata:
wikipedia.output(u'\03{lightred}ERROR 80: NON TROVO IL TEMPLATE\03{default}')
templateText = u'{{Corpo celeste\n'
for record in listaOrdinata:
templateText += u'|' + record[0] + u' = ' + record[1] + '\n'
templateText += u'}}'
regex = re.compile(u'{{[Cc]orpo[ _]celeste.*?}}',re.DOTALL)
(text,n) = regex.subn(templateText,text)
if n==0:
wikipedia.output(u'\03{lightred}ERROR 81: NON TROVO IL TEMPLATE!\03{default}')
return text
def run(self):
Riga 284 ⟶ 555:
page = wikipedia.Page(self.site,nomePagina)
while page.isRedirectPage():
page = pagewikipedia.getRedirectTargetoutput(u'La pagina è un REDIRECT, seguo il redirect')
page = page.getRedirectTarget()
try:
text = page.get()
if not page.canBeEdited():
wikipedia.output(u"\03{lightred}ERRERROR 90 You can't edit page %s\03{default}" % page.aslink())
continue
except wikipedia.NoPage:
wikipedia.output(u'\03{lightred}ERRERROR 120 Page %s not found\03{lightdefault}' % page.aslink())
continue
except wikipedia.IsRedirectPage:
wikipedia.output(u'\03{lightyellow}FATAL ERRERROR 100 Page is redirect.\03{default}')
 
old_text = text
 
text = self.fixTemplate(text)
if dati[1]!='':
wikipedia.output(u'\03{lightgreen}Nome alternativo: %s' %dati[1])
Riga 327 ⟶ 601:
text = self.spettro(text,dati[9])
message += 'classe spettrale, '
 
text = self.ordinaTemplate(text,self.templatesWithParams(text))
 
if text!=old_text:
wikipedia.output(' -------------diff-----diff-------------------')
wikipedia.showDiff(old_text,text)
wikipedia.output(' -----------------------------------------')
wikipedia.setAction(message[:-2])
if not self.acceptall:
choice = wikipedia.inputChoice(u'Do you want to accept these changes?', ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
if choice in ['a', 'A']:
self.acceptall = True
if choice in ['y', 'Y']:
page.put_async(text)
if self.acceptall:
try:
page.put(text)
except wikipedia.EditConflict:
wikipedia.output(u'Skipping %s because of edit conflict' % (page.title(),))
except wikipedia.SpamfilterError, e:
wikipedia.output(u'Cannot change %s because of blacklist entry %s' % (page.title(), e.url))
except wikipedia.PageNotSaved, error:
wikipedia.output(u'\03{lightred}ERROR 10 putting page: %s\03{default' % (error.args,))
except wikipedia.LockedPage:
wikipedia.output(u'Skipping %s (locked page)' % (page.title(),))
else:
wikipedia.output('\03{lightyellow}WARNING 30 Nessuna modifica da fare\03{default}')
 
def filterArg(gen,argomento,valore):
Riga 387 ⟶ 682:
def main():
s = wikipedia.Site('it')
filename = "lista_asteroidi.txt"
lista = open(filename, 'r')
 
csv.register_dialect('dialettoAsteroidi',delimiter='|')
gen = UnicodeReader(lista, 'dialettoAsteroidi')
 
filename = "lista_asteroidi.txt"
first = None
number = None
argomento = None
valore = None
 
 
for arg in wikipedia.handleArgs():
Riga 406 ⟶ 700:
elif arg.startswith('-number'):
if len(arg) == 7:
number = int(wikipedia.intputinput('Primo numero:'))
else:
number = int(arg[8:])
elif arg.startswith('-list'):
if len(arg) == 5:
filename = wikipedia.input('Lista dati:')
else:
filename = arg[6:]
else:
array = arg.split(':')
Riga 415 ⟶ 714:
valore = array[1]
argomento = arg2int(argomento[1:])
 
lista = open(filename, 'r')
csv.register_dialect('dialettoAsteroidi',delimiter='|')
gen = UnicodeReader(lista, 'dialettoAsteroidi')
 
 
Riga 431 ⟶ 734:
bot = botAsteroidi(gen)
bot.run()
wikipedia.output(u'Lista finita')