Translate

This commit is contained in:
Rnhmjoj 2014-12-13 19:00:25 +01:00
parent 4fd1320da2
commit 87fa98e018

View File

@ -5,17 +5,14 @@ from re import compile
url = 'https://galilei-cr-sito.registroelettronico.com/' url = 'https://galilei-cr-sito.registroelettronico.com/'
url_main = url + 'news' url_main = url + 'news'
url_login = url + 'login' url_login = url + 'login'
url_voti = url + 'votes/?s=' url_marks = url + 'votes/?s='
materie = {} subjects = {}
br = mechanize.Browser()
br.set_handle_robots(False)
br = RoboBrowser(history=False) br = RoboBrowser(history=False)
def login(user, password): def login(user, password):
'''Effetua l'autenticazione''' '''Authenticate the user'''
br.open(url_login) br.open(url_login)
# Fill in the login form # Fill in the login form
@ -24,56 +21,52 @@ def login(user, password):
form['password'].value = password form['password'].value = password
br.submit_form(form) br.submit_form(form)
# Se non compare 'errati' si è autenticati # Check if authenticated
if 'errati' in br.response.text: if 'errati' in br.response.text:
return False return False
else:
return True return True
def medie(): def means():
'''Calcola la medie per ogni materia''' '''Compute mean for each subject'''
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)
for i in subjects.keys(): for i in subjects.keys():
yield _mean(list(get_marks(i))) 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(): def get_name():
'''Resituisce il dizionario delle materie dello studente''' '''Find the student's name from the registry'''
br.open(url_main) 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): def get_subjects():
'''Restituisce la lista dei voti per materia''' '''Create a reversed dictionary of type (subject, id)'''
html = br.open(url_voti + str(materie[materia])) br.open(url_main)
testo = bs4.BeautifulSoup(html).get_text() links = br.get_links(href=compile('votes/\?s=\d+'))
regex = re.compile('(\d{1,2}(\+|-|\.\d{1,2})?) \(.{3}\)') return {i.text.capitalize(): i.attrs['href'][-7:] for i in links}
voti = [i[0] for i in re.findall(regex, testo)]
return _converti(voti)
def _converti(lista): def get_marks(subject):
'''Converte la lista con i voti da str in float''' '''Returned the list of marks for a subject'''
voti = [] br.open(url_marks + str(subjects[subject]))
for i in lista: 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: try:
# Voti del tipo 6.5
voti.append(float(i))
# Voti del tipo 7+
yield float(i) yield float(i)
except ValueError: except ValueError:
if i == 'A': if i == 'A':
@ -85,70 +78,61 @@ def _converti(lista):
elif i[1] == '-': elif i[1] == '-':
yield float(i[0]) - 0.25 yield float(i[0]) - 0.25
elif i[2] == '-': elif i[2] == '-':
voti.append(float(i[:-1]) - 0.25)
return voti
yield float(i[:-1]) - 0.25 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) marks = list(marks)
return sum(marks) / len(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 def _show_means():
print('Media generale: %.2f' % media_generale) '''Show general mean and for each subject [Procedure]'''
for id, (materia, voto) in enumerate(zip(materie.keys(), voti)): # Print id, subject, mean for every subject
print('%d. %s - Media: %.2f' % (id + 1, materia, voto))
print('Media generale: %.2f' % _mean(means())) print('Media generale: %.2f' % _mean(means()))
for id, (subject, voto) in enumerate(zip(subjects.keys(), means())): for id, (subject, voto) in enumerate(zip(subjects.keys(), means())):
print('%d. %s: %.2f' % (id + 1, subject, voto)) print('%d. %s: %.2f' % (id + 1, subject, voto))
def _mostra_voti(): def _show_marks():
'''Mostra i voti per la materie scelta [Procedura]''' '''Prompt for a subject and show the marks [Procedure]'''
for i, materia in enumerate(materie.keys()): for i, subject in enumerate(subjects.keys()):
print('%d. %s' % (i + 1, materia)) print('%d. %s' % (i + 1, subject))
while True: while True:
print('') print('')
id = int(input('Materia: ')) id = int(input('Materia: '))
if id in range(15): if id in range(15):
nome = materie.keys()[id - 1] name = list(subjects.keys())[id - 1]
voti = get_voti(nome) print(name)
print(nome) print('Voti:', *get_marks(name))
print('Voti:', *voti) print('Media: %.2f' % _mean(get_marks(name)))
print('Media: %.2f' % _media(voti))
else: else:
print('Inserire numero corretto!') print('Inserire numero corretto!')
def main(): def main():
# Autenticazione # Authentication
logged = False logged = False
while not logged: while not logged:
user, password = input('Username: '), getpass('Password: ') user, password = input('Username: '), getpass('Password: ')
logged = login(user, password) logged = login(user, password)
if not logged: if not logged:
print('Autenticazione fallita, riprovare.') print('Autenticazione fallita, riprovare.')
print('Connesso come %s.\n' % get_nome()) print('Connesso come %s.\n' % get_name())
global materie # So we don't need to recompute every time
materie = get_materie() global subjects
subjects = get_subjects()
#Menu # Menu
while True: while True:
mode = input('Scegli [v]oti o [m]edie: ') mode = input('Scegli [v]oti o [m]edie: ')
print('') print('')
if scelta == 'v': if mode == 'v':
_mostra_voti() _show_marks()
elif scelta == 'm': elif mode == 'm':
_mostra_medie() _show_means()
input() input()
if __name__ == '__main__': if __name__ == '__main__':