Utente:Wisbot/asteroidi.py

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca
# -*- coding: utf-8 -*-
"""
Modifiche asteroidi

-first:X                      Primo asteroide su cui agisce, poi segue
                              l'ordine della lista
                              
-number:N                     Numeri su cui agisce, agisce su tutti che hanno
                              numero>=N
                              
-argomento:A                  Agisce solo sugli asteroidi che hanno un certo
                              argomento non nullo
                              
-valore:V                     Agisce solo sugli asteroidi che hanno un certo
                              argomento con un certo valore (usare con
                              l'opzione -argomento)

"""
#
# [[Utente:Wiso]] 2008
#
# Distributed under the terms of the GPL licence
#


from __future__ import generators
from datetime import date
from time import strptime
import sys, re
import wikipedia, pagegenerators,config
import csv, codecs, cStringIO

mesi=['gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre']

def int2mese(n):
    return mesi[n-1]

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                            dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')



class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

    def __iter__(self):
        return self

    def next(self):
        return self.reader.next().encode("utf-8")

class UnicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)

    def next(self):
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]

    def __iter__(self):
        return self

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        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):
        regex = re.compile(name2regex(campo) + ' ?= ?(.+)')
        match = regex.search(text)
        if match:
            return match.group(1)
        return False

    def campo_esiste(self,campo,text):
        regex = re.compile('\| ?' + name2regex(campo))
        match = regex.search(text)
        if match:
            return True
        return False

    def inserisci_da_zero(self,text,campo,argomento):
        regex = re.compile(u'({{ ?[Cc]orpo celeste.+?)}}',re.DOTALL)
        newtext = regex.sub('\\1'+'|' + campo + ' = ' + argomento + '\n}}',text)
        return newtext

    def inserisci_da_vuoto(self,text,campo,argomento):
        regex = re.compile(u'\| ?' + name2regex(campo) + ' ?= ?')
        newtext = regex.sub('|' + campo + ' = ' + argomento,text)
        return newtext

    def aggiungi_da_non_vuoto(self,text,campo,argomento,separator=u''):
        regex = re.compile(u'\| ?' + name2regex(campo) + ' ?= ?(.+)')
        match = regex.search(text)
        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)
        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():
                    if aggiungi:
                        wikipedia.output(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)
                text = self.inserisci_da_vuoto(text,campo,valore)
        return text

    def aggiungi_cat(self,text,cat):
        """
        Aggiunge una categoria. Se la categoria è già presente non fa nulla. La
        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}ERROR 40: NON RIESCO AD INSERIRE LA STRINGA %s ALLA FINE DELLA PRIMA FRASE\03{default}' %new)
        return text
    
    def sostituisci_testo(self,text,regex,new):
        (newtext,n) = regex.subn(new,text)
        if text != newtext:
            wikipedia.output(u'Sostituisco testo con %s' %new)
        if n==0:
            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}ERROR 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):
        campo = u'albedo'
        return self.campo(text,campo,al)

    def per_rot(self,text,per):
        campo = u'periodo_rotaz'
        per += ' ore'
        return self.campo(text,campo,per)

    def diam(self,text,diam):
        campo = u'diametro_med'
        diam += ' km'
        text = self.aggiungi_testo(text,' del diametro medio di circa %s' %diam)
        return self.campo(text,campo,diam)

    def data(self,text,giorno,mese,anno):
        mese = int2mese(int(mese))
        campo = u'data'
        valore = '[[%s %s]] [[%s]]' %(giorno,mese,anno)
        text = self.campo(text,campo,valore)

        regex = re.compile(u'([sS])coperto nel \[\[([0-9]+)\]\]')
        new = '\\1coperto nel [[%s]]' %anno
        text = self.sostituisci_testo(text,regex,new)
        return text

    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

    def orbit(self,text,orbit):
        regex_descrizione = re.compile(u'è un \[\[asteroide\]\] del \[\[sistema solare\]\]')
        oldcat = wikipedia.Page(self.site,u'Asteroidi del sistema solare')
        newcat = None
        if orbit in ('MBA','IMB','OMB'):
            new_template = u'[[Fascia principale]]'
            new_descrizione = u'è un [[asteroide]] della [[fascia principale]]'
            newcat = u'Asteroidi della fascia principale'          
        elif orbit == 'TJN':
            new_template = u'[[asteroide troiano]]'
            new_descrizione = u'è un [[asteroide troiano]]'
            newcat = u'Asteroidi troiani'
        elif orbit == 'AMO':
            new_template = u'[[asteroide Amor]]'
            new_descrizione = u'è un [[asteroide NEAR]]'
            newcat = u'Asteroidi Amor'
        elif orbit == 'APO':
            new_template = u'[[asteroide Apollo]]'
            new_descrizione = u'è un [[asteroide NEAR]]'
            newcat = u'Asteroidi Apollo'
        elif orbit == 'ATE':
            new_template = u'[[asteroide Aten]]'
            new_descrizione = u'è un [[asteroide NEAR]]'
        elif orbit == 'CEN':
            new_template = u'[[Centauro (astronomia)|asteroide centauro]]'
            new_descrizione = u'è un [[Centauro (astronomia)|asteroide centauro]]'
        elif orbit == 'TNO':
            new_template = u'[[Oggetto trans-nettuniano]]'
            new_descrizione = u'è un [[oggetto trans-nettuniano]]'
        elif orbit == 'MCA':
            new_template = u'[[asteroide areosecante]]'
            new_descrizione = u'è un [[asteroide areosecante]]'
            cat = u'Asteroidi areosecanti'
            text = self.aggiungi_cat(text,cat)
        else:
            wikipedia.output(u'\03{lightred}ERROR 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:
            newcat = wikipedia.Page(self.site,newcat)
            text = wikipedia.replaceCategoryInPlace(text, oldcat, newcat)
            text = self.fix_category(text)
        return text

    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):
        for dati in self.gen:
            message = 'Bot: inserisco/modifico dati su: '
            nomePagina = dati[0]
            wikipedia.output('\03{lightpurple} >>> %s <<<\03{default}' %nomePagina)
            page = wikipedia.Page(self.site,nomePagina)
            while page.isRedirectPage():
                wikipedia.output(u'La pagina è un REDIRECT, seguo il redirect')
                page = page.getRedirectTarget()            
            try:
                text = page.get()
                if not page.canBeEdited():
                    wikipedia.output(u"\03{lightred}ERROR 90 You can't edit page %s\03{default}" % page.aslink())
                    continue
            except wikipedia.NoPage:
                wikipedia.output(u'\03{lightred}ERROR 120 Page %s not found\03{lightdefault}' % page.aslink())
                continue
            except wikipedia.IsRedirectPage:
                wikipedia.output(u'\03{lightyellow}FATAL ERROR 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])
                message += 'nome alternativo, '
                text = self.nome_alternativo(text,dati[1])
            if dati[2]!='' and dati[3]!='' and dati[4]!='':
                wikipedia.output(u'\03{lightgreen}Data scoperta: %s %s %s\03{default}' %(dati[2],dati[3],dati[4]))
                message += 'data scoperta, '
                text = self.data(text,dati[2],dati[3],dati[4])
            if dati[5]!='':
                wikipedia.output(u'\03{lightgreen}Orbit: %s\03{default}' %dati[5])
                text = self.orbit(text,dati[5])
                message += 'orbita, '
            if dati[6]!='':
                wikipedia.output(u'\03{lightgreen}Albedo: %s\03{default}' %dati[6])
                text = self.albedo(text,dati[6])
                message += 'albedo, '
            if dati[7]!='':
                wikipedia.output(u'\03{lightgreen}per_rot: %s\03{default}' %dati[7])
                text = self.per_rot(text,dati[7])
                message += 'rotazione, '
            if dati[8]!='':
                wikipedia.output(u'\03{lightgreen}Diametro: %s\03{default}' %dati[8])
                text = self.diam(text,dati[8])
                message += 'diametro, '
            if dati[9]!='':
                wikipedia.output(u'\03{lightgreen}Classe spettrale: %s\03{default}' %dati[9])
                text = self.spettro(text,dati[9])
                message += 'classe spettrale, '

            text = self.ordinaTemplate(text,self.templatesWithParams(text))

            if text!=old_text:
                wikipedia.output('    ------------------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):
    for data in gen:
        if data[argomento] == valore:
            yield data

def filterArgIs(gen,argomento):
    for data in gen:
        if data[argomento]:
            yield data

def filterNumber(gen,primo_numero):
    regex = re.compile(u'[0-9]+')
    primo_numero = int(primo_numero)
    for data in gen:
        titolo = data[0]
        numero = int(regex.search(titolo).group(0))
        if numero >= primo_numero:
            yield data

def filterFirst(gen,first):
    for data in gen:
        if data[0] == first:
            yield data
            break
    for data in gen:
        yield data

def arg2int(argomento):
    if argomento in (u'mese',u'Mese'):
        return 3
    elif argomento in (u'giorno',u'Giorno'):
        return 2
    elif argomento in (u'anno',u'Anno'):
        return 4
    elif argomento in (u'nome alternativo',u'nomealternativo',u'nome_alternativo'):
        return 1
    elif argomento in (u'orbit',u'Orbit',u'orbita',u'Orbita'):
        return 5
    elif argomento in (u'albedo',u'Albedo'):
        return 6
    elif argomento in (u'periodo',u'Periodo',u'rotazione',u'Rotazione'):
        return 7
    elif argomento in (u'diametro',u'Diametro'):
        return 8
    elif argomento in (u'classe',u'Classe'):
        return 9
    else:
        wikipedia.output(u'ARGOMENTO %s NON VALIDO' %argomento)
        return None
    

def main():
    s = wikipedia.Site('it')
    


    filename = "lista_asteroidi.txt"
    first = None
    number = None
    argomento = None
    valore = None


    for arg in wikipedia.handleArgs():
        if arg.startswith('-first'):
            if len(arg) == 6:
                first = wikipedia.input('Prima pagina:')
            else:
                first = arg[7:]
        elif arg.startswith('-number'):
            if len(arg) == 7:
                number = int(wikipedia.input('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(':')
            argomento = array[0]
            if len(array) == 2:
                valore = array[1]
            argomento = arg2int(argomento[1:])

    lista = open(filename, 'r')
    
    csv.register_dialect('dialettoAsteroidi',delimiter='|')
    gen = UnicodeReader(lista, 'dialettoAsteroidi')


    if first:
        gen = filterFirst(gen,first)
    elif number:
        gen = filterNumber(gen,number)
    elif argomento:
        if valore:
            gen = filterArg(gen,argomento,valore)
        else:
            gen = filterArgIs(gen,argomento)
        
                
    bot = botAsteroidi(gen)
    bot.run()
    wikipedia.output(u'Lista finita')


if __name__ == "__main__":
    try:
        main()
    finally:
        wikipedia.stopme()