Home > Mobile >  Is there something special to encrypting a string into another file using a custom dictionary?
Is there something special to encrypting a string into another file using a custom dictionary?

Time:02-13

I made a custom dictionary in Python changing the alphabet (both upper and lowercase) into symbols and numbers. I am trying to copy the content of one text file to another but encrypt it in the custom dictionary. For example, if the file says "Hello World" the other file that it is being copied to should say "%?;;2 !2(;". I tried a bunch of things but it either gives me an error or the other file stays blank

Here's the code below

fileData = open('EXAMPLE.txt', 'r')
f = open('ENCODE.txt', 'w')

for x in fileData:
    encrypt = code.get(x, '')
    f.write(encrypt)

fileData is the file the is being read/ copied from. code is the dictionary name. Then I tried getting the value from the key or if it is a number/ white space, it will just default. However, it keeps coming out blank. I tried the import json but I also can not get that to encrypt with the dictionary.

EXAMPLE.txt has the text

the quick brown fox jumps over the lazy dog
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

ENCODE.txt is blank as the text will be copied over and encoded

Dictionary below

code = {'A':'1',
         'a':'@',
         'B':'!',
         'b':'#',
         'C':'3',
         'c':'$',
         'D':'4',
         'd':'^',
         'E':'<',
         'e':'?',
         'F':'>',
         'f':',',
         'G':'5',
         'g':'/',
         'H':'%',
         'h':']',
         'I':'[',
         'i':'£',
         'J':'|',
         'j':'*',
         'K':'-',
         'k':' ',
         'L':'8',
         'l':')',
         'M':'9',
         'm':'(',
         'N':'&',
         'n':'7',
         'O':';',
         'o':'`',
         'P':'0',
         'p':'_',
         'Q':'"',
         'q':'~',
         'R':'.',
         'r':'2',
         'S':'6',
         's':'8',
         'T':'7',
         't':'=',
         'U':'[',
         'u':'>',
         'V':'{',
         'v':';',
         'W':'}',
         'w':':',
         'X':'é',
         'x':'¡',
         'Y':'»',
         'y':'¤',
         'Z':'§',
         'z':'µ'}

CodePudding user response:

for x in fileData: iterates lines of text. You need something like the following to read a single character at a time:

while (x := fileData.read(1)):

But there is also str.translate and str.maketrans which are built-in methods of string to generate lookup tables and perform translation, so you can read the whole file and translate efficiently:

Python 3.10 example:

xlat = str.maketrans('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz',
                     '1@!#3$4^<?>,5/%][£|*- 8)9(&7;`0_"~.2687=[>{;}:é¡»¤§µ')

with (open('EXAMPLE.txt', 'r') as fileData,
      open('ENCODE.txt', 'w') as f):

    encrypt = fileData.read().translate(xlat)
    f.write(encrypt)
  • Related