I'm working on a code for a school which tells the students how many times they can skip classes. It doesn't work because there is an specific mistake that is always appearing:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__
return self.func(*args)
File "/Users.py", line 52, in inicio
for line in improt:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 25: ordinal not in range(128)
I already tried to import mtTkinter but the program didn't recognize it. The mistake says tkinter is getting the wrong number of args. The line that caused the error was this one:
for line in importar:
lista.append(line)
But that seems like the right number of arguments, so what's going on?
There are also some strange mistakes that keep the program to run well.
Here I put my code so you can see if it works.
from tkinter import*
import math
import tkinter.filedialog
import traceback
import sys
ventana=Tk()
ventana.title("Este programa le dice cuantas veces mas puede faltar de ausencias 1, 2 y 3")
ventana.geometry("1000x1000")
lista=[]
clas=Label(ventana, text="Si tu materia es Tecno, Frances o Edufis, escribela tal cual en el cuadro").place(x=50,y=90)
classe=Entry(ventana)
classe.place(x=50,y=110)
segu=Label(ventana, text="Si tu materia es Español o Actualidad, escribela tal cual en el cuadro").place(x=50,y=140)
segun=Entry(ventana)
segun.place(x=50,y=160)
tercis=Label(ventana, text="Si tu materia es Qui, Math, Ingles o Filosofia, escribela tal cual en el cuadro").place(x=50,y=190)
terce=Entry(ventana)
terce.place(x=50,y=220)
a=Label(ventana, text="¿Cuantas veces ha faltado por ausencias o retardos 1?").place(x=50,y=250)
aa=Entry(ventana)
aa.place(x=50,y=270)
b=Label(ventana, text="¿Cuantas veces ha faltado por ausencias o retardos 2?").place(x=50,y=300)
bb=Entry(ventana)
bb.place(x=50,y=320)
c=Label(ventana, text="¿Cuantas veces ha faltado por ausencias o retardos 3?").place(x=50,y=350)
cc=Entry(ventana)
cc.place(x=50,y=380)
def inicio ():
global lista
global classe
global segu
global tercis
global aa
global bb
global cc
clases=(Entry.get(classe))
materias = filedialog.askopenfilename(filetypes=(("Archivo de texto","*.txt"),("Cualquier archivo","*.*")))
improt = open(materias,"r")
for line in improt:
lista.append(line)
if clases== Tecno:
Tecno= lista(0)
if clases== Frances:
Frances= lista(1)
if clases== Edufis:
Edufis= lista(2)
for i in range (0,2):
total=70
AM= (total*15)/100
A=(Entry.get(aa))
if A<AM:
res= AM-A
print("le quedan ", res, " ausencias o retardos 1")
if A==AM:
print("No puede tener mas ausencias o retardos 1")
if A>AM:
print("Ya se paso del maximo de ausencias o retardos 1")
segunda=(Entry.get(segun))
if segun== Español:
Español= lista(3)
if segun== Actualidad:
Actualidad= lista(4)
for i in range(3,4):
totala=140
BM= (totala*15)/100
B=(Entry.get(bb))
if B<AM:
tes= AM-B
print("le quedan ", tes, " ausencias o retardos 2")
if B==AM:
print("No puede tener mas ausencias o retardos 2")
if B>AM:
print("Ya se paso del maximo de ausencias o retardos 2")
tercera=(Entry.get(terce))
if terce== Qui:
Qui= lista(5)
if terce== Math:
Math= lista(6)
if terce== Ingles:
Ingles= lista(7)
if terce== Filo:
Filo= lista(8)
for i in range (5,8):
totale=175
CM= (totale*15)/100
C=(Entry.get(cc))
if C<BM:
pes= BM-C
print ("le quedan ", pes, " ausencias o retardos 2")
if C==BM:
print ("No puede tener mas ausencias o retardos 2")
if C>BM:
print ("Ya se paso del maximo de ausencias o retardos 2")
improt.close()
escoge = Button(ventana, text = "Escoge un archivo y despues escribe tu materia en el cuadro que corresponda", command = inicio).place(x =45, y = 30)
cierra = Button(ventana, text = "Cierra", command = ventana.destroy).place(x = 50, y = 420)
ventana.mainloop()
It looks like your system default is ASCII
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 25: ordinal not in range(128)
Assuming the language the file is using is Latin-1, try adding
#! /usr/bin/python ## (your shebang may be slightly different)
# -*- coding:latin-1 -*-
## next line after the shebang
## and then
for line.decode('latin-1') in improt:
If you open the file in Firefox and then View > Text Encoding, it should say what the encoding is. There are also websites that will do this. Also, this is a common problem (not a rare exception) so a search for "UnicodeDecodeError: 'ascii' codec can't decode byte" should produce a lot of hits
Related
EDIT
I've a text file containing sentences including emojis that I cannot handle correctly.
My csv file contains those sentences :
Je suis sur que certaines personnes vont faire la file pour toucher cette borne unicode-d83d\ude02
Aurelie Gouverneur voir même la lechée peut être unicode-d83d\ude02unicode-d83d\ude02unicode-d83e\udd2e
Mélanie Ham même ce prendre en photo avec unicode-d83e\udd23
My code :
df_test=pd.read_csv("myfile.csv", sep=';',index_col=None, encoding="utf-8")
for item, row in df_test.iterrows():
print(repr(row["Message"]))
s=row["Message"]
s = re.sub(r'unicode-([0-9a-f]{4})',lambda m: chr(int(m.group(1),16)),s)
s = s.encode('utf16','surrogatepass').decode('utf16')
The printed results :
'Je suis sur que certaines personnes vont faire la file pour toucher cette borne unicode-d83d\\ude02'
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-40-e3c423a15acd> in <module>
5 s=row["Message"]
6 s = re.sub(r'unicode-([0-9a-f]{4})',lambda m: chr(int(m.group(1),16)),s)
----> 7 s = s.encode('utf16','surrogatepass').decode('utf16')
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 162-163: illegal UTF-16 surrogate
The issue is probably related to the encoding when I load the csv into a dataframe, but I've no idea how to solve this...
The text is a combination of a Unicode escape and a custom syntax. This will decode as described by capturing the hexadecimal values of the two escape codes, then formatting them into a JSON-formatted pair of surrogates and letting that module convert to the correct Unicode code point.
#coding:utf8
import re
import json
sentences = [r'Je suis sur que certaines personnes vont faire la file pour toucher cette borne unicode-d83d\ude02',
r'Aurelie Gouverneur voir même la lechée peut être unicode-d83d\ude02unicode-d83d\ude02unicode-d83e\udd2e',
r'Mélanie Ham même ce prendre en photo avec unicode-d83e\udd23']
def surrogates_to_unicode(m):
upper = int(m.group(1),16)
lower = int(m.group(2),16)
return json.loads(f'"\\u{upper:04x}\\u{lower:04x}"')
for s in sentences:
s = re.sub(r'unicode-([0-9a-f]{4})\\u([0-9a-f]{4})',surrogates_to_unicode,s)
print(s)
Je suis sur que certaines personnes vont faire la file pour toucher cette borne 😂
Aurelie Gouverneur voir même la lechée peut être 😂😂🤮
Mélanie Ham même ce prendre en photo avec 🤣
I'm currently working on a little side project yet having multiple issues. I'm reading a file within the folder where the project is that holds data for 10 users.
As for the code itself...it's pretty big.
def ouvrir_fichier(nomFichier):
""" Ne pas oublier les docstring
"""
try:
fp = open(nomFichier, 'r')
return fp
except:
return print("Le fichier n'existe pas. Veuillez réessayer.")
def lire_fichier(fp):
""" Ne pas oublier les docstring"""
# Lis n et initialise une liste vide --
# où il y a une liste vide pour chaque usager du réseau
# ensuite lis le reste du fichier et ajouter l'information à reseau
liste1 = fp.readlines()
n = int(liste1[0])
liste2 = liste1[1:]
reseau = [[] for i in range(n)]
for i in liste2:
i = i.replace("\n", "")
data = i.split(" ")
valeur1 = int(data[0])
valeur2 = int(data[1])
reseau[valeur1].append(valeur2)
reseau[valeur2].append(valeur1)
fp.close()
return reseau
def trouver_nombre_elements_communs_entre_listes(liste1, liste2):
""" Ne pas oublier les docstring"""
compteur_amis_commun = 0
for element in liste1:
if element in liste2:
compteur_amis_commun = compteur_amis_commun + 1
return compteur_amis_commun
def initialiser_matrice(n):
"""
Crée une matrice nxn, initialisée avec des zéros et retourne la matrice.
Args:
n (int): dimension de la matrice nxn
Returns:
matrice (list): matrice initialisée
"""
matrice = []
for ligne in range(n): # pour chacune des lignes dans n
matrice.append([]) # créer une ligne (liste) et l'initialiser à 0
for colonne in range(n):
matrice[ligne].append(0) # ajouter un 0 pour chaque n colonne
return matrice
def calculer_scores_similarite(reseau):
""" Ne pas oublier les docstring"""
n = len(reseau)
matrice_similarite = initialiser_matrice(n)
liste1 = []
liste2 = []
compteur_liste1 = 0
compteur_liste2 = 0
for element_liste1 in reseau:
liste1 = element_liste1
for element_liste2 in reseau:
liste2 = element_liste2
compteur_amis_commun = trouver_nombre_elements_communs_entre_listes(liste1, liste2)
matrice_similarite[compteur_liste1][compteur_liste2] = compteur_amis_commun
compteur_liste2 = compteur_liste2 + 1
compteur_liste1 = compteur_liste1 + 1
compteur_liste2 = 0
return matrice_similarite
def recommander(id_usager,reseau,matrice_similarite):
""" Ne pas oublier les docstring"""
usager_matrice = matrice_similarite.index(id_usager)
ami_recommande = matrice_similarite.index(max(usager_matrice))
max_value = max(matrice_similarite.index(usager_matrice))
if ami_recommande == id_usager:
max_value = max_value - 1
ami_recommande = matrice_similarite.index(max_value)
while True:
if ami_recommande == reseau.index(ami_recommande):
ami_recommande = reseau.index(max_value, ami_recommande + 1)
return True
return ami_recommande
def main():
nomFichier = input("Nom du fichier contenant le réseau: ")
reseau = lire_fichier(ouvrir_fichier(nomFichier))
n = len(reseau)
matrice_similarite = calculer_scores_similarite(reseau)
while True:
while True:
id_usager = int(input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}):".format(n)))
if 0 <= id_usager and id_usager < n:
calculer_scores_similarite(reseau)
print("Pour la personne" , id_usager , ", nous recommandons l'ami" , recommander(id_usager, reseau, matrice_similarite))
continue
else:
print("Erreur: l'usager doit être un nombre entier entre ", 0, "et", n - 1, "inclusivement.\n")
autreRecommandation = input("Voulez-vous une autre recommandation (oui/non)?")
if autreRecommandation.lower() == "oui":
return True
else:
print("Merci d'avoir utiliser le programme de recommandation d'amis.")
break
if __name__ == "__main__":
main()
Most of the content seems to be working fine until I get to part where I need to recommend a user identification. I'll try to work on the doc string as well in the meantime but I could totally use a little bit of help as to debug this. I tested most of the code on another .py project until I hit the function recommander
First Edit:
I did forget to apply the return. I changed it and it is now in the def. Now however...I seem to be having this error.
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevd.py", line 1668, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevd.py", line 1662, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevd.py", line 1072, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/101136/PycharmProjects/tp2/TP2.py", line 132, in <module>
main()
File "C:/Users/101136/PycharmProjects/tp2/TP2.py", line 119, in main
print("Pour la personne" , id_usager , ", nous recommandons l'ami" , recommander(id_usager, reseau, matrice_similarite))
File "C:/Users/101136/PycharmProjects/tp2/TP2.py", line 89, in recommander
usager_matrice = matrice_similarite.index(id_usager)
ValueError: 0 is not in list
Also I'm wondering about a little something. The part where I ask for an input to define id_usager in the def main(), I was wondering if there was a way to also treat characters as well as integers. Integers, I got it covered with my code but if somebody wants to write boy instead of a number, it'll fail.
accessing element of list is done by list_name[index], list_name.index(element) returns the index of that element,if they are two in the list it returns the index of the first one, if the element is not there,it throws a ValueError: "element" is not in the list.
in your case
change
usager_matrice = matrice_similarite.index(id_usager)
to
usager_matrice =matrice_similarite[id_usager]
and other places you want to access element of a list using index
in the scond question from the comment, check if its numeric like this
id_usager =input("Entrer l'ID de l'usager pour lequel vous voulez une recommandation (entre 0 et {}):".format(n))
if not id_usager.isdigit():
continue
id_user=int(id_usager)
note that this will convert also floats into int
I'm testing a query with python and sqlite3. First method works fine, but
second is not working. It is about the defined type of variable containing the resgisters in DB:
import sqlite3
def insertar():
db1=sqlite3.connect('tabla.db')
print("Estas en la funcion insertar")
nombre1=raw_input("Escribe el titulo de la novela: ")
autor1=raw_input("Escribe el autor de la novela: ")
year1=str(input("Digita el any de la novela: "))
consulta=db1.cursor()
strConsulta = "insert into tabla(nombre, autor, year) values\
('"+nombre1+"','"+autor1+"','"+year1+"')"
print(strConsulta)
consulta.execute(strConsulta)
consulta.close()
db1.commit()
db1.close()
def consultar():
db2 = sqlite3.connect("tabla.db")
print("Estas en la funcion insertar")
db2row_factory = sqlite3.Row
consulta = db2.cursor()
consulta.execute("select * from tabla")
filas = consulta.fetchall()
lista = []
for fila in filas:
s = {}
s['nombre'] = fila['nombre']
s['autor'] = fila['autor']
s['year'] = str(fila['year'])
lista.append(s)
consulta.close()
db2.close()
return(lista)
#consultar()
def menu():
Opcion= input("\nIngresa la opcion deseada\n1.Inserta un valor en la tabla\n2.Consultar los valores de la tabla\n")
if Opcion==1:
insertar()
menu()
elif Opcion==2:
ListaNovelas = consultar()
for novela in ListaNovelas:
print(novela['nombre'],novela['autor'],novela['year'])
menu()
menu()
I get this error while testing the second method consultar().
$ python file.py
Ingresa la opcion deseada
1.Inserta un valor en la tabla
2.Consultar los valores de la tabla
2
Estas en la funcion insertar
Traceback (most recent call last):
File "insertar.py", line 56, in <module>
menu()
File "insertar.py", line 51, in menu
ListaNovelas = consultar()
File "insertar.py", line 33, in consultar
s['nombre'] = fila['nombre']
TypeError: tuple indices must be integers, not str
db2row_factory = sqlite3.Row
This is the problematic line. Instead you meant to set the row_factory factory on the db2 connection instance:
db2.row_factory = sqlite3.Row
Then, all the fetched rows would be now sqlite3.Row instances having dictionary-like access to field values.
I'm coding a project, in which I have 2 files (dataStructure.py and calculUser.py) working together and 1 which is a test file.
In structureDonnees.py I have this function which reads a dataset containing cars and builds data structures :
# -*-encoding:utf-8-*-
import csv
import sys #pour utiliser maximum et minimum du type float
from calculUser import *
from trajetUser import *
def recupVoiture() :
#nom de la base de donnée
nomFichier = 'CO2_passenger_cars_v10.csv'
#on ouvre le fichier en lecture
opener = open(nomFichier, "r")
#On ouvre le fichier nomFichier en lecture
lectureFichier = csv.reader(opener, delimiter='\t')
#le dico contenant les carburants
fuelType = dict()
#le dico contenant les voitures
voiture = dict()
#le dico contenant les émissions de CO2 en g/km
emission = dict()
#minimum et maximum emission
min_emission = sys.float_info.max #initialisé à max(float) pour que l'on soit sûr que toutes les emissions soient plus petites
max_emission = sys.float_info.min #initialisé à min(float) pour que l'on soit sûr que toutes les emissions soient plus grandes
for row in lectureFichier :
#Si la colonne existe
if row:
#construction du dictionnaire voiture
if voiture.has_key(row[10]) :
if row[11].upper() not in voiture[row[10]] : voiture[row[10]].append("%s" %row[11].upper()) #on ajoute le modèle
else :
voiture[row[10]] = [] #on crée une liste vide contenant les modèles et leurs versions
voiture[row[10]].append("%s" %row[11]) #on ajoute le modèle et sa version
#construction du dictionnaire fuelType
if fuelType.has_key(row[10]) : fuelType[row[10]].append(row[19].upper()) #ajout du type de carburant utilisé par la voiture correspondante dans voiture{}
else :
fuelType[row[10]] = [] #on crée une liste vide contenant les carburants
fuelType[row[10]].append(row[19]) #ajout du type de carburant utilisé par la voiture correspondante dans voiture{}
#construction du dictionnaire emission
if emission.has_key(row[10]) :
emission[row[10]].append(row[14]) #ajout de la quantité de CO2 émise par la voiture correspondante dans voiture{}
min_emission = minEmission(float(row[14]), min_emission)
max_emission = maxEmission(float(row[14]), max_emission)
else :
emission[row[10]] = [] #on crée une liste vide contenant les émissions en CO2
fuelType[row[10]].append(row[14]) #ajout de la quantité de CO2 émise par la voiture correspondante dans voiture{}
min_emission = minEmission(float(row[14]), min_emission)
max_emission = maxEmission(float(row[14]), max_emission)
#On ferme le fichier
opener.close()
#La valeur de retour est un tableau contenant les structures de données générées.
res = [voiture, fuelType, emission, min_emission, max_emission]
return res
In the calculUser.py, I defined the minEmission and maxEmission function :
def minEmission(emissionFichier, min_emission) :
if emissionFichier < min_emission :
min_emission = emissionFichier
return min_emission
def maxEmission(emissionFichier, max_emission) :
if emissionFichier > max_emission :
max_emission = emissionFichier
return max_emission
When I'm executing test.py, I get an error with this line :
table = recupVoiture()
Traceback (most recent call last):
File "test.py", line 13, in <module>
tableau = recupVoiture()
File "/home/user/Polytech/ge3/ProjetPython/structureDonnees.py", line 60, in recupVoiture
min_emission = minEmission(float(row[14]), min_emission)
NameError: global name 'minEmission' is not defined
I don't understand why I get this error. By executing everything except test.py I get no error but when I do it doesn't execute due to this minEmission and maxEmission not defined.
Is it because I'm calling a function when I'm defining a function?
How could I fix it?
I fixed the problem, it seems like my functions minEmission() and maxEmission() couldn't do a reference to max_emission and min_emission since those variables are declared in structureDonnees.py and not in calculUser.py.
I fixed it by creating an intermediary variable which takes the value of min_emission and max_emission and which is returned, instead of min_emission and max_emission.
Plus, I had to do a : from calculUser import minEmission, maxEmissiondirectly in the recupVoiture() function. I know that's awful but it solved the problem. I'll use it until I find a better, cleaner solution.
Thanks for the help guys, I'll do a better post/code if I have to ask any other help ! :)
Just discovered this forum and it's unbelievable how helpful its community is. Well, I have an issue trying to make a "while" loop on Python. I want the program's menu to repeat until you select Option 6 - Salir (Exit). Everything is fine at first, but after I select an option and the program prints x thing, I press enter to return to the menu or continue (just like when you use a pause on C) and get an error.
Juan es un empleado mexicano comun con poco salario minimo. Que quiere saber de el? MENU
1.Salario
2.Sombrero
3.Playera
4.Pantalones
5.Tenis
6.Salir
Seleccione una opcion 1 El salario de Juan es 7.5
MENU
1.Salario
2.Sombrero
3.Playera
4.Pantalones
5.Tenis
6.Salir
Seleccione una opcion Traceback (most recent call last): File "C:\Users\joguzman\Documents\Proyectos Eclipse\Clases\src\main.py", line 22, in <module>
opcion=int(input("\nSeleccione una opcion\n")) ValueError: invalid literal for int() with base 10: ''
I also want it to clear the screen, which doesn't happen at all. Here's my code:
import os class empleadoClass: #las propiedades que tendra cada empleado
salario=7.5
sombrero='nike'
playera='polo'
pantalones='patito'
tenis='adidas'
juanObject = empleadoClass() #'juanObjeto' esta "heredando" propiedades de empleadoClass
print ("Juan es un empleado mexicano comun con poco salario minimo. Que quiere saber de el?") opcion=1
while (opcion!=6):
print("MENU \n1.Salario \n2.Sombrero \n3.Playera \n4.Pantalones \n5.Tenis \n6.Salir")
opcion=int(input("\nSeleccione una opcion\n"))
if (opcion==1):
print ("El salario de Juan es ",juanObject.salario)
os.system('pause>nul')
os.system('cls')
elif (opcion==2):
print ("La marca del sombrero de Juan es ",juanObject.sombrero)
os.system('pause>nul')
os.system('cls')
elif (opcion==3):
print ("La marca de la playera de Juan es ",juanObject.playera)
os.system('pause>nul')
os.system('cls')
elif (opcion==4):
print ("La marca de los pantalones de Juan es ",juanObject.pantalones)
os.system('pause>nul')
os.system('cls')
elif (opcion==5):
print ("La marca de los tenis de Juan es ",juanObject.tenis)
os.system('pause>nul')
os.system('cls')
elif(opcion==6):
print ("Gracias por usar nuestro programa!")
else:
print ("Ingrese una opcion correcta")
os.system('pause>nul')
os.system('cls')
Thanks in advance! :D And sorry for any grammar mistakes, as you can see I'm not a native english speaker.
EDIT: It seems the code's structure got a messy when posting... Does anyone know how to solve this? :/
I think a simpler way to do a menu like this is to:
def print_menu():
# print stuff here, 6 exits
while True:
print_menu()
try:
choice = int(input('>>'))
if choice == 1:
blah
elif choice == 2:
more blah
elif choice == 6:
break
except ValueError:
handle_error()
As for clearing the screen that depends on what OS you are using and how you are running the program. See this question - how to clear the screen in python