From 87fa98e018a6e882d50b3dd249479b893d6968f2 Mon Sep 17 00:00:00 2001 From: Rnhmjoj Date: Sat, 13 Dec 2014 19:00:25 +0100 Subject: [PATCH] Translate --- pymarks.py | 132 +++++++++++++++++++++++------------------------------ 1 file changed, 58 insertions(+), 74 deletions(-) diff --git a/pymarks.py b/pymarks.py index c3c3206..c85b6c0 100644 --- a/pymarks.py +++ b/pymarks.py @@ -5,17 +5,14 @@ from re import compile url = 'https://galilei-cr-sito.registroelettronico.com/' url_main = url + 'news' url_login = url + 'login' -url_voti = url + 'votes/?s=' +url_marks = url + 'votes/?s=' -materie = {} - -br = mechanize.Browser() -br.set_handle_robots(False) +subjects = {} br = RoboBrowser(history=False) def login(user, password): -'''Effetua l'autenticazione''' + '''Authenticate the user''' br.open(url_login) # Fill in the login form @@ -24,56 +21,52 @@ def login(user, password): form['password'].value = password br.submit_form(form) - # Se non compare 'errati' si รจ autenticati + # Check if authenticated if 'errati' in br.response.text: return False - else: - return True + return True -def medie(): - '''Calcola la medie per ogni materia''' - medie = [] - for i in materie.keys(): - medie.append(_media(get_voti(i))) - return medie - - -def get_nome(): - '''Estrapola [cit.] il nome dello studente dal registro''' - news = br.open(url_main) +def means(): + '''Compute mean for each subject''' for i in subjects.keys(): yield _mean(list(get_marks(i))) - # Prende il contenuto del tag 'h2' con ID 'student_name' - soup = bs4.BeautifulSoup(news) - nome = soup.find('h2', {'id': 'student_name'}, text=True).contents[0].split() - return ' '.join([nome[-1]] + nome[:-1]) -def get_materie(): - '''Resituisce il dizionario delle materie dello studente''' +def get_name(): + '''Find the student's name from the registry''' br.open(url_main) - links_materie = br.links(url_regex=re.compile('votes/\?s=\d+')) - return {i.text.capitalize(): i.url[-7::] for i in links_materie} + + # Get the content of 'h2' tag with ID 'student_name' + name = br.select('h2#student_name')[0].text.split() + return ' '.join([name[-1]] + name[:-1]) -def get_voti(materia): - '''Restituisce la lista dei voti per materia''' - html = br.open(url_voti + str(materie[materia])) - testo = bs4.BeautifulSoup(html).get_text() - regex = re.compile('(\d{1,2}(\+|-|\.\d{1,2})?) \(.{3}\)') - voti = [i[0] for i in re.findall(regex, testo)] - return _converti(voti) +def get_subjects(): + '''Create a reversed dictionary of type (subject, id)''' + br.open(url_main) + links = br.get_links(href=compile('votes/\?s=\d+')) + return {i.text.capitalize(): i.attrs['href'][-7:] for i in links} -def _converti(lista): - '''Converte la lista con i voti da str in float''' - voti = [] - for i in lista: +def get_marks(subject): + '''Returned the list of marks for a subject''' + br.open(url_marks + str(subjects[subject])) + res = br.find_all(text=compile(r'^(\d{1,2}(\+|-|\.\d{1,2})?) ')) + return _parse(i[0:-1] for i in res) + + +def _parse(marks): + ''' + Parse marks into floats: + NC -> 0 + A -> nothing + n+ -> n + 0.25 + n- -> n - 0.25 + n -> n + ''' + for i in marks: try: - # Voti del tipo 6.5 - voti.append(float(i)) - # Voti del tipo 7+ yield float(i) except ValueError: if i == 'A': @@ -85,70 +78,61 @@ def _converti(lista): elif i[1] == '-': yield float(i[0]) - 0.25 elif i[2] == '-': - voti.append(float(i[:-1]) - 0.25) - return voti - yield float(i[:-1]) - 0.25 -def _media(voti): - '''Calcola la media di una lista di voti''' - return sum(voti) / len(voti) +def _mean(marks): + '''Mean of a list of marks''' marks = list(marks) return sum(marks) / len(marks) -def _mostra_medie(): - '''Mostra le medie per ogni materia e generale [Procedura]''' - voti = medie() - media_generale = _media(voti) - # Scrive numero, nome e media per ogni materia - print('Media generale: %.2f' % media_generale) - for id, (materia, voto) in enumerate(zip(materie.keys(), voti)): - print('%d. %s - Media: %.2f' % (id + 1, materia, voto)) +def _show_means(): + '''Show general mean and for each subject [Procedure]''' + # Print id, subject, mean for every subject print('Media generale: %.2f' % _mean(means())) for id, (subject, voto) in enumerate(zip(subjects.keys(), means())): print('%d. %s: %.2f' % (id + 1, subject, voto)) -def _mostra_voti(): - '''Mostra i voti per la materie scelta [Procedura]''' - for i, materia in enumerate(materie.keys()): - print('%d. %s' % (i + 1, materia)) +def _show_marks(): + '''Prompt for a subject and show the marks [Procedure]''' + for i, subject in enumerate(subjects.keys()): + print('%d. %s' % (i + 1, subject)) while True: print('') id = int(input('Materia: ')) if id in range(15): - nome = materie.keys()[id - 1] - voti = get_voti(nome) - print(nome) - print('Voti:', *voti) - print('Media: %.2f' % _media(voti)) + name = list(subjects.keys())[id - 1] + print(name) + print('Voti:', *get_marks(name)) + print('Media: %.2f' % _mean(get_marks(name))) else: print('Inserire numero corretto!') def main(): - # Autenticazione + # Authentication logged = False while not logged: user, password = input('Username: '), getpass('Password: ') logged = login(user, password) if not logged: print('Autenticazione fallita, riprovare.') - print('Connesso come %s.\n' % get_nome()) + print('Connesso come %s.\n' % get_name()) - global materie - materie = get_materie() + # So we don't need to recompute every time + global subjects + subjects = get_subjects() - #Menu + # Menu while True: mode = input('Scegli [v]oti o [m]edie: ') print('') - if scelta == 'v': - _mostra_voti() - elif scelta == 'm': - _mostra_medie() + if mode == 'v': + _show_marks() + elif mode == 'm': + _show_means() input() if __name__ == '__main__':