Python Forum
Issues with character conversion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issues with character conversion
#1
So I'm trying to learn python and I came up with an idea for a little program that reads a text file, converts all of the characters into pseudo-random ones, and then creates a key to return it to human readable form. The issue is that, when I decode the message sometimes one character will get decoded incorrectly. So all 'a' characters might show up as '0', or 'M', etc.



import random
import pickle
import copy


"""
Encodes and decodes files
"""


def load(string):
    """
    function that converts characters to pseudo-random
    characters and creates a key to decipher later.
    """

    ## APPEND PATH HERE*
    ## opens file to store converted data in
    datafile = open('/your/path/here/data.dep', 'wb')
    ## oens file to store key in
    keyfile = open('/your/path/here/key.dep', 'wb')
    ## defines some default values
    key = []
    user_string = []
    working_pool = {}
    out_key = {}
    new_string = []

    ## character map, gets copied to create character pools
    all_char = ['a', 'b', 'c', 'd', 'e',
                'f', 'g', 'h', 'i', 'j',
                'k', 'l', 'm', 'n', 'o',
                'p', 'q', 'r', 's', 't',
                'u', 'v', 'w', 'x', 'y',
                'z', 'A', 'B', 'C', 'D',
                'E', 'F', 'G', 'H', 'I',
                'J', 'K', 'L', 'M', 'N',
                'O', 'P', 'Q', 'R', 'S',
                'T', 'U', 'V', 'W', 'X',
                'Y', 'Z', '0', '1', '2',
                '3', '4', '5', '6', '7',
                '8', '9', '!', '@', '#',
                '$', '%', '^', '&', '*',
                '+', '-', '_', '=', '~',
                ' ', '.', ',', ';', '(',
                ')', '<', '>', '?', ':',
                '|', '/', '~', '[', ']',
                '{', '}', '\'', '"', '\t',
                '\n', '\\']
    ## above list copied
    char_copy = copy.deepcopy(all_char)
    pool = copy.deepcopy(all_char)

    ## for each character in the character map,
    for char in char_copy[:]:
        ## pick a random character from pool
        temp_char = random.choice(pool)
        ## appends working_pool dictionary
        ## {'random': 'actual'} EXAMPLE
        working_pool[temp_char] = char
        ## appends my_key dictionary, creates key
        ## {'actual': 'random'} EXAMPLE
        out_key[char] = temp_char
        ## remove the random character assigned
        ## from the pool so it cant be picked twice
        pool.remove(temp_char)

    ## opens user defined file supplied by function parameter
    with open(string) as infile:
        ## while true, examine each character
        while True:
            ## append 'user_string' with each character in file
            ch = infile.read(1)
            user_string.append(ch)
            ## if the character is in the conversion pool
            if ch in working_pool:
                ## convert character
                new_string.append(working_pool[ch])
            else:
                ## keep character as is
                new_string.append(ch)
            ## repeat until EOF
            if not ch:
                eof = 'true'
                break
        ## start DEBUG
        #test = ''.join(str(z) for z in new_string)
        #ustring = ''.join(str(y) for y in user_string)
        #print(test)
        #print('\n')
        #print(ustring)
        #print(working_pool)
        ## end DEBUG

    ## serializes converted string and stores it
    pickle.dump(new_string, datafile)
    pickle.dump(out_key, keyfile)
    datafile.close()
    keyfile.close()

def unload(data, key):
    """
    function that, given the correct keyfile,
    will translate converted string to human
    readable clear text
    """

    ## opens files supplies by function parameter
    input_file = open(data, 'rb')
    decoder = open(key, 'rb')

    active = True
    ## while active is true
    while active:
        try:
            ## dump data into 'contents' until EOF
            contents = pickle.load(input_file)
        except EOFError:
            ## if EOF, active is false
            active = False


    ## same as above but for decoder
    active = True
    while active:
        try:
            load_key = pickle.load(decoder)
        except EOFError:
            active = False

    ## sets empty list for converting
    converted_string = []
    ## for each value in the encrypted data,
    for ch in contents[:]:
        ## if the value is in the key,
        if ch in load_key:
            ## add the decoded character to converted_string
            converted_string.append(load_key[ch])
        #else:
            #converted_string.append(ch)

    clear_text = ''.join(str(e) for e in converted_string)
    ## start DEBUG
    #print('\n')
    #print(load_key)
    ## end DEBUG
    ## print unencrypted results
    print(clear_text)
    input_file.close()
    decoder.close()


## CALL FUNCTIONS HERE
load('/fake/data/someFile.txt')
unload('/your/path/here/data.dep', '/foo/bar/key.dep')
any help or general python advice is greatly appreciated :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] unexpected character after line continuation character paul18fr 4 3,438 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  SyntaxError: unexpected character after line continuation character siteshkumar 2 3,199 Jul-13-2020, 07:05 PM
Last Post: snippsat
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 2,767 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  Replace changing string including uppercase character with lowercase character silfer 11 6,232 Mar-25-2019, 12:54 PM
Last Post: silfer
  SyntaxError: unexpected character after line continuation character Saka 2 18,588 Sep-26-2017, 09:34 AM
Last Post: Saka

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020