Outils pour utilisateurs

Outils du site


issue152:python

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
issue152:python [2019/12/30 08:26] – créée d52frissue152:python [2020/01/04 14:34] (Version actuelle) auntiee
Ligne 1: Ligne 1:
-Lately, I've been doing some work with a computer book publisher on Machine Learning and Python. It's a very interesting subject, and I really enjoy the learning process on all of the various modeling methods.+***Lately, I've been doing some work with a computer book publisher on Machine Learning and Python. It's a very interesting subject, and I really enjoy the learning process on all of the various modeling methods.
  
 You want pickle with that? You want pickle with that?
  
-One thing that I've found is that when you need to (or want to) save some of the data in the middle of a process, often the pickle library is used. I've known about pickle for a long time, but have really never messed with it much, so I thought I'd explore some.+One thing that I've found is that when you need to (or want to) save some of the data in the middle of a process, often the pickle library is used. I've known about pickle for a long time, but have really never messed with it much, so I thought I'd explore some.**
  
-Pickle or olive?+Dernièrement, j'ai travaillé un peu avec un éditeur de livre électronique sur l'Apprentissage Machine et Python. C'est un sujet très intéressant et j'ai vraiment apprécié le processus d'apprentissage sur toutes les différentes méthodes de modélisation. 
 + 
 +Voulez-vous des cornichons avec ? 
 + 
 +Une chose que j'ai découverte est que, si vous avez besoin de (ou si vous voulez) sauvegarder des données au milieu du processus, la bibliothèque pickle (cornichon) est utilisée. Je connais pickle depuis longtemps, mais je ne me suis jamais beaucoup mesuré à lui ; aussi, je me suis dit que je devrais l'explorer un peu. 
 + 
 +**Pickle or olive?
  
 An olive is a wonderful thing in a martini. It doesn't do anything for Python code. It is, however, a type of non-venomous Python mainly in Australia. An olive is a wonderful thing in a martini. It doesn't do anything for Python code. It is, however, a type of non-venomous Python mainly in Australia.
  
-Pickle on the other hand, is a method to serialize and deserialize Python object structures. If you know all there is to know about Pickles, feel free to jump forward in the article. If not, or if you trust me to teach you something, keep reading.+Pickle on the other hand, is a method to serialize and deserialize Python object structures. If you know all there is to know about Pickles, feel free to jump forward in the article. If not, or if you trust me to teach you something, keep reading.**
  
-Serializing means to take an object from memory, convert it into a stream of bytes that can be stored on disk. De-serializing is the reverse of the process. Let's say you have a dictionary. You can't just dump it to disk from memory. You have to convert it into a format that lends itself to being a disk file. JSON, XML, HTML all jump to mind. Pickles are just another way to do this. There's a library that handles all the tough stuff for you.+Cornichon ou olive ?
  
-What can you pickle? Well most Python objects can be pickled, but there are a few that can't. While you can pickle simple objects (Integersfloats, complex numbers and strings), you normally would pickle Tuples, Lists, sets and Dictionaries that are built from most objects. However, things like generators, lambda functions and defaultdicts can not be pickled. There are some workaroundsbut this is pretty much the rule of thumb.+Une olive est un élément merveilleux dans le martini. Elle ne fait rien pour le code Python. C'estcependantune variété non venimeuse de python en Australie.
  
-Pickling Process+En revanche, pickle est une méthode pour sérialiser et dé-sérialiser des structures objet de python. Si vous connaissez déjà tout ce qu'il faut savoir sur Pickles, n'hésitez pas à sauter plus avant dans l'article. Sinon, ou si vous pensez que je peux vous apprendre quelque chose, continuez la lecture.  
 + 
 +**Serializing means to take an object from memory, convert it into a stream of bytes that can be stored on disk. De-serializing is the reverse of the process. Let's say you have a dictionary. You can't just dump it to disk from memory. You have to convert it into a format that lends itself to being a disk file. JSON, XML, HTML all jump to mind. Pickles are just another way to do this. There's a library that handles all the tough stuff for you. 
 + 
 +What can you pickle? Well most Python objects can be pickled, but there are a few that can't. While you can pickle simple objects (Integers, floats, complex numbers and strings), you normally would pickle Tuples, Lists, sets and Dictionaries that are built from most objects. However, things like generators, lambda functions and defaultdicts can not be pickled. There are some workarounds, but this is pretty much the rule of thumb.** 
 + 
 +« Sérialiser » signifie prendre un objet en mémoire et le convertir en un flux de bits que vous pouvez sauvegarder sur disque. Dé-sérialiser est le processus inverse. Disons que nous avons un dictionnaire. Vous ne pouvez pas le passer en bloc de la mémoire au disque. Vous devez le convertir dans un format qui l'amène à devenir un fichier qui ira sur le disque. JSON, XML, HTML viennent immédiatement à l'esprit. Pickle est simplement une autre façon de le faire. Une bibliothèque existe qui gère pour vous tout ce bazar touffu. 
 + 
 +Qu'est-ce que vous pouvez « pickler » ? Eh bien ! La plupart des objets en Python peuvent être « picklés » mais quelques-uns ne peuvent pas l'être. Alors que vous pouvez utiliser pickle sur des objets simples (nombres entiers, flottants ou complexes, et chaînes), vous utiliserez pickle normalement sur des tuples, des listes, des ensembles et des dictionnaires qui sont construits avec la plupart de ces objets. Cependant, les choses comme des générateurs, des fonctions lambda et des defaultdics ne peuvent pas être « picklées ». Il y a des contournements, mais c'est généralement le cas. 
 + 
 +**Pickling Process
  
 I want to thank my friend Halvard Tislavoll from Norway for the idea and the code for this part. I want to thank my friend Halvard Tislavoll from Norway for the idea and the code for this part.
Ligne 21: Ligne 37:
 Let's say that you want to create a dataset of colors that can be used when creating a GUI. Tkinter (as well as other GUI toolkits) allows you to use hex codes as well as color names. There are many web pages that show all the colors along with the color name for quick reference, but what if you needed all of them along with their hex values? Let's say that you want to create a dataset of colors that can be used when creating a GUI. Tkinter (as well as other GUI toolkits) allows you to use hex codes as well as color names. There are many web pages that show all the colors along with the color name for quick reference, but what if you needed all of them along with their hex values?
  
-Under Ubuntu, there is a file located in the /etc/X11 folder called rgb.txt. Make a copy of it and put the copy into a working folder.+Under Ubuntu, there is a file located in the /etc/X11 folder called rgb.txt. Make a copy of it and put the copy into a working folder.** 
 + 
 +Processus pour « pickler » 
 + 
 +Je veux remercier mon ami norvégien Halvard Tislavoll pour l'idée et le code de cette partie de l'article. 
 + 
 +Disons que vous voulez créer un jeu de couleurs qui pourraient être utilisées pour créer une interface utilisateur graphique (GUI). Tkinter (comme d'autres boîtes à outils pour les GUI) vous permet d'utiliser des codes hexadécimaux et des noms de couleurs. De nombreuses pages Web existent qui présentent toutes les couleurs avec leurs noms pour un recherche rapide ; mais, qu'en est-il si vous avez besoin de ces noms accompagnés de leurs codes hexadécimaux ? 
 + 
 +Sous Ubuntu, il existe un fichier situé dans le dossier /etc/x11, appelé rgb.txt. Faites-en une copie et mettez-le dans votre dossier de travail.
  
-Please note that Halvard's coding style is not the same as mine and I'm sure that it's not the same as yours. However, I'm sure that you will be able to understand his code.+**Please note that Halvard's coding style is not the same as mine and I'm sure that it's not the same as yours. However, I'm sure that you will be able to understand his code.
  
 Now we can get started creating a program to convert this text to a dictionary and pickle it. Name your program file "rgb2pickle.py". First, you need to import the pickle library Now we can get started creating a program to convert this text to a dictionary and pickle it. Name your program file "rgb2pickle.py". First, you need to import the pickle library
Ligne 30: Ligne 54:
  
 Now, let's define an empty list and empty dictionary... Now, let's define an empty list and empty dictionary...
 +
 +myList = []
 +myDict = {}**
 +
 +Notez, s'il vous plaît, que le style de codage de Halvard n'est pas le même que le mien et je suis sûr qu'il n'est pas le même que le vôtre. Cependant, je suis sûr que vous saurez comprendre son code.
 +
 +Maintenant, nous pouvons commencer à créer un programme pour convertir ce texte en dictionnaire, puis le traiter avec pickle. Nommez votre fichier de programme « rgb2pickle.py ». D'abord, vous devez importer la bibliothèque pickle :
 +
 +import pickle
 +
 +Maintenant, définissons une liste vide et un dictionnaire vide :
  
 myList = [] myList = []
 myDict = {} myDict = {}
  
-Next, we'll want to create some support functions. First the function that will read the rgb.txt file and return the contents in a list (see next page, top right).+**Next, we'll want to create some support functions. First the function that will read the rgb.txt file and return the contents in a list (see next page, top right).
  
 This function takes the decimal value and returns the hex value using the above helper functions (next page, bottom right). This function takes the decimal value and returns the hex value using the above helper functions (next page, bottom right).
Ligne 40: Ligne 75:
 This function takes the list and puts everything into a dictionary... This function takes the list and puts everything into a dictionary...
  
 +def txt2dict(myList):
 +    i = 0
 +    aDict = {}
 +    for item in myList:
 +        newList = []
 +# pick name, clean it for tab
 +        name = item[13:].lstrip("\t")
 +        name = name.rstrip()
 +# pick RGB values (dec)
 +        R = item[0:3].lstrip()
 +        R = emptystring(R)
 +        G = item[4:7].lstrip()
 +        G = emptystring(G)
 +        B = item[8:11].lstrip()
 +        B = emptystring(B)**
 +        
 +Ensuite, nous créerons quelques fonctions support. D'abord, la fonction qui lira le fichier rgb.txt et retournera le contenu sous forme de liste (voir page suivante, en haut à droite).
 +
 +Cette fonction prend la liste et met tout dans un dictionnaire :
  
 def txt2dict(myList): def txt2dict(myList):
Ligne 57: Ligne 111:
         B = emptystring(B)         B = emptystring(B)
  
-Now, convert the RGB values to a hex value…+**Now, convert the RGB values to a hex value…
  
 # convert dec2hex value # convert dec2hex value
Ligne 69: Ligne 123:
  
 # make a list with a new column structure # make a list with a new column structure
 +        newList.append(name)
 +        newList.append(R)
 +        newList.append(G)
 +        newList.append(B)
 +        newList.append(H)
 +        aDict[i] = newList
 +        i += 1
 +    return aDict**
 +    
 +Maintenant, convertissons les valeurs RGB en valeur hexadécimale :
 +    
 +# convertir la valeur dec2hex
 +H1 = dec2hex(R)
 +H2 = dec2hex(G)
 +H3 = dec2hex(B)
 +# contruire la valeur en #
 +H = f"#{H1}{H2}{H3}"
 +
 +Et rajoutons cela à la structure en liste et mettons à jour le dictionnaire :
 +
 +# faire une liste avec une nouvelle structure en colonnes
         newList.append(name)         newList.append(name)
         newList.append(R)         newList.append(R)
Ligne 78: Ligne 153:
     return aDict     return aDict
  
-Now that all of the helper functions are done, let's put them all together (next page, top right).+**Now that all of the helper functions are done, let's put them all together (next page, top right).
  
 The terminal output is very uninteresting and responds very quickly. Now, we have a pickle file, what do we do with it? The terminal output is very uninteresting and responds very quickly. Now, we have a pickle file, what do we do with it?
 +
 Depickling a pickle Depickling a pickle
  
Ligne 86: Ligne 162:
  
 Here is a quick code snippet that you can use in a CLI application… Here is a quick code snippet that you can use in a CLI application…
 +
 +with open(filename, 'rb') as f:
 +    data = pkl.load(f)**
 +
 +Maintenant que toutes les fonctions d'aide sont faites, rassemblons-les (page suivante, en haut à droite).
 +
 +La sortie sur le terminal est très intéressante et répond très rapidement. Maintenant nous avons un fichier pickle ; que faire avec lui ?
 +
 +« Dé-pickler » un pickle
 +
 +Dé-pickler (ou dé-sérialiser) est tout aussi facile que de créer le fichier pickle une fois que vos données sont prêtes.
 +
 +Voici un rapide bout de code que nous pouvons utiliser dans une appli en ligne de commande :
  
 with open(filename, 'rb') as f: with open(filename, 'rb') as f:
     data = pkl.load(f)     data = pkl.load(f)
  
-This works well only if the pickle file was created with Python 3. If, however, it was created with Python 2 and the cPickle routine, it will probably error out. An easy workaround for this is (shown bottom right).+**This works well only if the pickle file was created with Python 3. If, however, it was created with Python 2 and the cPickle routine, it will probably error out. An easy workaround for this is (shown bottom right).
  
 Anyway, for my purposes I wanted to be able to actually see the data in its raw form, direct from the pickle file. I threw together a quick Page form and threw in a very little code (THANK YOU Page!) and here is the result… Anyway, for my purposes I wanted to be able to actually see the data in its raw form, direct from the pickle file. I threw together a quick Page form and threw in a very little code (THANK YOU Page!) and here is the result…
  
-I won’t bore you with the details of how to do this in Page, since there’s only three buttons, an entry widget, two labels, and a scrolled text widget. We’ve already covered that. However, I will show you the code that is important in the _support file. I really didn’t worry about any error checking for the simple project.+I won’t bore you with the details of how to do this in Page, since there’s only three buttons, an entry widget, two labels, and a scrolled text widget. We’ve already covered that. However, I will show you the code that is important in the _support file. I really didn’t worry about any error checking for the simple project.** 
 + 
 +Ça marche bien seulement si le fichier pickle a été créé avec Python 3. Cependant, s'il a été créé avec Python 2 et la routine cPickle, il a des chances de sortir une erreur. Une solution de repli facile est (voir en bas à droite). 
 + 
 +De toute manière, pour mes besoins, je voulais être capable en fait de voir les données sous une forme brute, directement depuis le fichier pickle. J'ai fait un rapide formulaire Page et y ai mis très peu de code (MERCI Page !) et voici le résultat : 
 + 
 +Je ne vous ennuierai pas avec les détails de comment le faire dans Page, car il n'y a que trois boutons, un gadget de saisie, deux étiquettes et un gadget de liste déroulante. Nous en avons déjà parlé. Cependant, je vous montrerai le code qui est important dans le fichier _support. Je ne me suis préoccupé d'aucune vérication d'erreur pour ce projet simple.
  
-We’ll look at the callback for the “get filename” button (the one that has “...” as its text) first (middle right). Basically, this simply calls a tkinter askopenfilename filedialog and puts the selected filename and path into the entry widget for display.+**We’ll look at the callback for the “get filename” button (the one that has “...” as its text) first (middle right). Basically, this simply calls a tkinter askopenfilename filedialog and puts the selected filename and path into the entry widget for display.
  
 Next is the callback for the “GO” button. This is where the real work is done. The logic is to: Next is the callback for the “GO” button. This is where the real work is done. The logic is to:
Ligne 103: Ligne 198:
 • Depickle it. • Depickle it.
 • Determine the type of data structure and display it. • Determine the type of data structure and display it.
-• Fill the text widget with the data from the structure (if possible).+• Fill the text widget with the data from the structure (if possible).**
  
-def on_btnGo():+Nous regarderons d'abord la fonction de rappel pour le bouton « get filename » (celui qui a « ... » comme texte)(en haut au milieu). En gros, cela appelle simplement un dialogue de fichier tkinter askopenfilename et met le fichier sélectionné et son chemin dans le gadget de saisie, pour affichage. 
 + 
 +Ensuite, vient la fonction de rappel pour le bouton « GO ». C'est ici que le vrai travail se fait. La logique est de : 
 +••Effacer le champ de texte. 
 +••Ouvrir le fichier que l'utilisateur a sélectionné dans la routine ci-dessus. 
 +••Le dé-pickler  
 +••Déterminer le type de la structure de données et l'afficher. 
 +••Remplir le gadget de texte avec les données de la structure (si possible). 
 + 
 + 
 +**def on_btnGo():
     # print('depickle1_support.on_btnGo')     # print('depickle1_support.on_btnGo')
     # sys.stdout.flush()     # sys.stdout.flush()
Ligne 118: Ligne 223:
 def clear_stw(): def clear_stw():
     # Clear the ScrolledText Widget     # Clear the ScrolledText Widget
 +    w.Scrolledtext1.delete('1.0', 'end')**
 +    
 +def on_btnGo():
 +    # print('depickle1_support.on_btnGo')
 +    # sys.stdout.flush()
 +    clear_stw()  # Effacer le gadget texte
 +
 +Voici le vrai code pour dépickler (page suivante, en haut à droite).
 +
 +Enfin, basé sur le type de données que nous avons, remplissez le gadget de texte (en bas à droite).
 +
 +La fonction pour effacer le gadget de texte est vraiment simple :
 +
 +def clear_stw():
 +    # Effacer le gadget ScrolledText
     w.Scrolledtext1.delete('1.0', 'end')     w.Scrolledtext1.delete('1.0', 'end')
  
-And the very last thing, just to be complete, is the Page provided function that defines the tkinter variables that allow easy setting of the text for the various widgets.+**And the very last thing, just to be complete, is the Page provided function that defines the tkinter variables that allow easy setting of the text for the various widgets.
  
 def set_Tk_var(): def set_Tk_var():
Ligne 129: Ligne 249:
     entry_var = tk.StringVar()     entry_var = tk.StringVar()
  
-That’s it.+That’s it.**
  
-Here is a good website that can help you understand the pickling process if you still want to learn more... https://www.datacamp.com/community/tutorials/pickle-python-tutorial+Et la toute dernière chose, juste pour être complet, est la fonction fournie par Page qui définit les variables tkinter qui permettent un paramétrage facile du texte pour les différents gadgets : 
 + 
 +def set_Tk_var(): 
 +    global pickleType 
 +    pickleType = tk.StringVar() 
 +    pickleType.set(''
 +    global entry_var 
 +    entry_var = tk.StringVar() 
 + 
 +Et c'est tout. 
 + 
 +**Here is a good website that can help you understand the pickling process if you still want to learn more... https://www.datacamp.com/community/tutorials/pickle-python-tutorial
  
 I’ve put the source files for the rgb2pickle.py file from Halvard on pastebin at: https://pastebin.com/s09mp72G I’ve put the source files for the rgb2pickle.py file from Halvard on pastebin at: https://pastebin.com/s09mp72G
Ligne 137: Ligne 268:
 And the python source for the Depickle GUI program there as well at: Depickle.py - https://pastebin.com/wsUMqk1F; Depickle_support.py - https://pastebin.com/TgmgngxJ And the python source for the Depickle GUI program there as well at: Depickle.py - https://pastebin.com/wsUMqk1F; Depickle_support.py - https://pastebin.com/TgmgngxJ
  
-Until next time, I hope you have a wonderful New Year and remember to keep coding!+Until next time, I hope you have a wonderful New Year and remember to keep coding!** 
 + 
 +Voici un bon site Web qui peut vous aider à comprendre le processus de pickling si vous voulez en apprendre plus...https://www.datacamp.com/community/tutorials/pickle-python-tutorial 
 + 
 +J'ai mis les fichiers source du fichier rgb2pickle.py venant de Halvard sur pastebin à : https://pastebin.com/s09mp72G 
 + 
 +Et les sources Python pour le programme de dé-pickling en interface graphique sont aussi à :  
 +Depickle.py - https://pastebin.com/wsUMqk1F 
 +Depickle_support.py - https://pastebin.com/TgmgngxJ 
 + 
 +En attendant la prochaine fois, je vous souhaite un merveilleux Nouvel An et n'oubliez pas de continuer à coder !
  
issue152/python.1577690816.txt.gz · Dernière modification : 2019/12/30 08:26 de d52fr