Outils pour utilisateurs

Outils du site


issue80:python_-_partie_50

This month, I thought I’d talk about a couple of lesser known functions, maketrans and translate. We’ll start with the translate method. The translate method returns a copy of a string – with all characters in the translate table replaced, or has the characters in the optional parameter deletechars removed from the string. Here’s the syntax.

s = str.translate(table[,deletecharacters])

Ce mois-ci , je vais parler de deux fonctions un peu moins connues : maketrans et translate. Nous allons commencer par la méthode translate. La méthode translate retourne une copie d'une chaîne, avec tous les caractères de la table translate remplacés (traduits) ou bien avec des caractères supprimés de la chaîne, s'ils sont contenus dans 'deletechars' (optionnel). Voici la syntaxe à utiliser : s = str.translate(table[,deletecharacters])

Before we get to the table portion of the method, let’s look at the delete portion. Let’s say that you have the string “The time has come”. And you want to delete all the vowels (for some weird reason) from that string. You can code it like this:

astr = “The time has come”

astr.translate(None,’aeiou’)

will return:

“Th tm hs cm”

Avant de passer à la partie 'table' de cette méthode, regardons la partie suppression. Disons que vous avez la chaîne «The time has come » et que vous voulez supprimer toutes les voyelles (pour une raison certes étrange, mais pourquoi pas) de cette chaîne. Vous pouvez coder comme ceci : astr = “The time has come” astr.translate (None,'aeiou') cela retourne : “Th tm hs cm”

Notice that we included None as the translate table. While this part is cool, it gets better. There is a function called maketrans. It takes an input string and an output string as parameters and returns a table that is used as the first parameter into the translate method. Here (top right) is a very simple example.

It returns:

“Th2 t3m2 h1s c4m2”

Notez que nous avons inclus « None » comme table de traduction. Bien que cette méthode soit déjà assez sympa, il y a mieux avec une autre méthode appelée « maketrans ». Cette méthode utilise une chaîne d'entrée et une chaîne de sortie en tant que paramètres et renvoie une table qui sera utilisée en tant que premier paramètre de la méthode « translate ». Vous trouverez, en haut à droite de cette page, un exemple très simple. Cela retourne : “Th2 t3m2 c4m2 H1S”

Let’s look at what this does. We assign intable to a string of vowels as before. outtable is assigned the numbers 1,2,3,4,5 as a string. When we make the call to maketrans, our actual trantable is as follows (shown below. The “\x” means that it is hexadecimal char):

If you look at it carefully, you’ll see that the lowercase vowel letters are replaced with the numbers we specified:

1bcd2fgh3jklmn4pqrst5vwxyz

Regardons comment ça marche… Nous attribuons « intable » à une chaîne de voyelles comme auparavant, « outtable » utilise les numéros 1,2,3,4,5 comme une chaîne. Lorsque nous faisons appel à « maketrans », notre « trantable » réelle est la suivante (illustrée ci-dessous “\x” signifie qu'il est de type char hexadécimal) : Si vous regardez attentivement, vous vous apercevrez que les voyelles minuscules sont remplacées par les chiffres que nous avons spécifiés : 1bcd2fgh3jklmn4pqrst5vwxyz

If you look even closer, you’ll see that there actually 256 entries starting with “\x00” and ending with “\xff”. So the table contains the entire 256 possible ascii character set. So, when the translate method gets the table, it iterates (or walks through) each character, getting that characters value in Hex, and then finds that value in the translate table and substitutes it in the output string. The Hex representation of our original astr string (‘The time has come’) is shown below.

So now it should be making sense.

Si vous regardez encore de plus près, vous verrez qu'il y a effectivement 256 entrées, en commençant par « \x00 » et en se terminant par « \xff ». Ainsi, le tableau contient l'ensemble des 256 codes possibles du jeu de caractères ascii. Ainsi, lorsque la méthode « translate » parcourt chaque caractère du tableau, elle obtient la valeur des caractères en hexadécimal, puis recherche la valeur dans le tableau « translate » et la remplace dans la chaîne de sortie. La représentation hexadécimale de notre chaîne « astr » originale (« The time has come ») est représentée ci-dessous. Maintenant, vous devez commencer à comprendre.

Now the purpose of this whole thing. Think back to your schooling where you learned about Julius Ceasar. Whenever he wanted to send a message of a confidential matter, he would use a cipher that would shift all the letters of the alphabet three characters to the right. So, using todays english alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

becomes: DEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABC

While this seems very simple by today’s standards, when I was a school kid, we used this all the time to send messages to each other. We used a different index into the string to start the encryption string, the logic behind it was the same.

Alors, à quoi tout cela peut-il servir ? Faites un retour en arrière et pensez à la période où vous avez étudié le personnage de Jules César à l'école… Lorsque César voulait envoyer un message à caractère confidentiel, il utilisait un chiffrement qui consistait à décaler, de trois caractères vers la droite, les lettres de l'alphabet. Ainsi, en utilisant l'alphabet latin d'aujourd'hui : ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz cela se transformait en : DEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABC Bien que cela semble très simple par rapport aux normes de chiffrement d'aujourd'hui, quand j'étais petit, nous utilisions également cette méthode de chiffrement pour envoyer des messages entre nous. Nous utilisions un indice (de décalage) différent pour démarrer la chaîne de chiffrement à un autre endroit mais la logique restait la même.

No one knows how effective this actually was for good old Julius. One would think that if someone intercepted the message, they would have thought that it was in some foreign language. We can only speculate.

We can easily use the translate method and the maketrans helper function to allow us to have fun with this. Let’s say we want to make a simple program that allows us to enter a string of “plain text” and get back an encrypted string using the same side right method that Caesar used. For simplicity sake, let’s only use uppercase characters (shown top right).

Personne ne sait si cette méthode fut un succès pour ce bon vieux Jules César mais on peut penser que si quelqu'un interceptait un tel message à l'époque, il aurait certainement cru qu'il s'agissait d'une langue étrangère ! Enfin, c'est ce que l'on peut supposer… Nous pouvons facilement utiliser la méthode « translate » et la fonction « maketrans » pour nous amuser un peu avec ça. Partons du principe que nous voulons faire un programme simple qui nous permet d'entrer une chaîne de « texte en clair » et d'obtenir en retour une chaîne cryptée en utilisant la même méthode de décalage à droite que celle utilisée par César. Par souci de simplicité, nous allons uniquement utiliser des caractères majuscules (voir en haut et à droite de cette page).

Everything in the above code is pretty much what we’ve covered above or in earlier Python articles, but I’ll go over it quickly.

The first two lines are the in and out strings. We’ve just shifted the characters and wrapped around to create the out string. The next two lines create a table for encoding and one for decoding. Line 5 prompts the user to enter a string to encode. We then encode that string (EncString) in the next line. To decode it, we simply use the translate method on the encoded string to get the plain text back. Finally we print both strings out. Here’s the output of the program.

Tout ce que vous trouverez dans le code ci-dessus est à peu près ce que nous avons vu au début de cet article ou dans les précédents articles sur Python, mais je vais expliquer rapidement… Les deux premières lignes représentent les chaînes d'entrée et de sortie. Nous avons juste déplacé les caractères vers la droite pour créer la chaîne de sortie. Les deux lignes suivantes représentent les fonctions d'encodage et de décodage. La ligne 5 invite l'utilisateur à saisir une chaîne à encoder. On encode alors cette chaîne (EncString) dans la ligne suivante. Pour décoder, nous utilisons simplement la méthode « translate » sur la chaîne codée pour obtenir le texte en clair. Enfin, nous affichons les deux chaînes. Voici ce qu'affiche le programme.

Enter the plaintext string → THE TIME HAS COME Encoded string is - WKH WLPH KDV FRPH Decoded string is - THE TIME HAS COME

Just like back in school. But let’s flesh it out just a bit to make it a bit more usable. The code is almost the same with a few exceptions. First, we have added a space to the end of the intab string and in between the “Z” and the “A” in the outtab string. This helps keep the actual words from being too obvious in the encrypted string. The next change is where we ask if the user wants to encode or decode the string. Finally we added an if statement to control what we print (shown bottom right).

Voilà, c'est comme à l'école ! Mais nous allons étoffer un peu notre code pour le rendre un peu plus utilisable. Le code est pratiquement le même à quelques exceptions près. Tout d'abord, nous avons ajouté une espace à la fin de la chaîne intab et entre le « Z » et le « A » dans la chaîne outtab. Cela permet de mieux cacher les mots d'origine dans notre chaîne cryptée. L'autre changement concerne l'endroit où nous demandons si l'utilisateur veut coder ou décoder la chaîne. Enfin , nous avons ajouté une instruction « if » pour contrôler ce que nous affichons (voir en bas et à droite).

The output from the program is:

La sortie du programme est :

Encode or Decode (E or D) → E Enter the string → THE TIME HAS COME Encoded string is - WKHCWLPHCKDVCFRPH

And to test the decode side of things:

Et pour tester le côté “décodage” de la chose : Encode or Decode (E or D) → D Enter the string → WKHCWLPHCKDVCFRPH Decoded string is - THE TIME HAS COME

Well, hopefully you are starting to get ideas about how to use this new information in your own code. See you next time!

Eh bien, j'espère que vous commencez à avoir des idées sur la façon d' utiliser ces nouvelles informations dans votre propre code. Rendez-vous la prochaine fois !

issue80/python_-_partie_50.txt · Dernière modification : 2014/05/07 10:55 de auntiee