1

I have a problem for school and I can't seem to figure it out. Basically, i'm in an intro to object oriented programming class, so I only need to complete this as basic as possible without using anything fancy that I haven't learned yet. Currently learning about dictionaries and sets, I need to use a dictionary that has a code written in it to encrypt a document that has a long string on one line.

So I need one part to read the dictionary and open the text file containing the string.

"The course Introduction to Object Oriented Programming uses the Python programming language."

I need to then use the code from this dictionary to encrypt it and write the encrypted version of the string to another text file called encrypt.txt.

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

This is the code I have so far. Any help would be greatly appreciated and an explanation in layman's terms would also be greatly appreciated.

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

def main():
    #Open the file you want to encrypt.
    infile = str(input('Enter the name of the input file: '))
    #read its contents
    dtext = open(infile, 'r')
    #read the line from the file
    dtext = dtext.readlines()

    #strip the newline
    #dtext = dtext.rstrip('\n')

    #call the encryptText function
    encryptText(dtext)

def encryptText(dtext):
    #enter the name of the file to write to
    outfile = str(input('Enter the name of the output file: '))
    #open the file to send encrypted text to
    etext = open(outfile, 'w')
    #set accumulator value
    count = 0
    #create a for loop to read each separate character
    for line in dtext:
        wordList = line.split()
        print(dtext, CODE[dtext])
    count += 1

main()
4
  • What went wrong? I got TypeError: unhashable type: 'list' ... is that what you see? Commented Mar 25, 2017 at 1:23
  • Yeah, but I think I figured out that part, but now i'm getting a new error... KeyError: ' ' Commented Mar 25, 2017 at 1:37
  • In my soltion I used dict.get(c,c) which tries to get the mapped c but otherwise passes the original through. For ascii text, it not encode things like tabs and newlines. Commented Mar 25, 2017 at 1:39
  • Side-note: This is a perfect case for str.translate. Just preprocess CODE = str.maketrans(CODE) (to fix up the key definitions), then converting through your table is just cipher = plain.translate(CODE). Commented Mar 25, 2017 at 1:41

3 Answers 3

1

You need to encrypt character by character and you need to take the result and build it back into a string. str.join turns a sequence of characters into a string and a generator can be written to encrypt each character... put them together and you have your solution.

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

def main():
    #Open the file you want to encrypt.
    infile = str(input('Enter the name of the input file: '))
    #read its contents
    dtext = open(infile, 'r')
    #read the line from the file
    dtext = dtext.readlines()

    #strip the newline
    #dtext = dtext.rstrip('\n')

    #call the encryptText function
    encryptText(dtext)

def encryptText(dtext):
    #enter the name of the file to write to
    outfile = str(input('Enter the name of the output file: '))
    #open the file to send encrypted text to
    etext = open(outfile, 'w')
    #set accumulator value

    #create a for loop to read each separate character
    for line in dtext:
        # encrypt character by character then join to a string
        encrypted = ''.join(CODE.get(c, c) for c in line)
        print(repr(line), repr(encrypted))
        etext.write(encrypted)
    etext.close()

main()
Sign up to request clarification or add additional context in comments.

7 Comments

For the record, given this appears to be Python 3, you could simplify dramatically. After defining CODE, add the line CODE = str.maketrans(CODE) to convert it to a str.translate friendly dict, then replace the genexpr and join with just encrypted = line.translate(CODE). Should be much faster, and you're using the most straightforward tool for the job.
@ShadowRanger - I agree there are better ways and ways this code could be cleaner but since this is for a newbie programming class, I wanted to disturb it as little as possible. If I was teaching a beginner class and got your solution I'd consider an F for cheating!
Really? I mean, if you look up str methods, str.translate is basically describing how you'd use a dict of exactly the form given (well, okay, it needs to be fixed up by maketrans to use the ordinals as keys, but close enough). It's actually more likely to be found by a newbie looking blindly than by a moderately experienced programmer who already knows "the right way to do it" but never encountered that specific method before.
I'm with tdelaney, I'm trying to to keep it as simple as possible because we haven't learned that much yet. As I do really appreciate learning more than i'm being taught, I need to learn it the easiest way possible at first for these labs! don't want to cheat haha
But your code worked tdelaney, except I don't think I have learned how to use join yet which is the only problem.
|
1

Strings are immutable. That means you cannot edit them after creation, in direct contrast to arrays. You will have to build a new string in order to encrypt your text. You will also likely need to do this one character at a time. Since you have the text of the file in dtext as a string, you can loop through the chars in the original string like so:

for i in range (0, len(dtext)):
    # add new character to string

(I'm breaking this apart so you cannot just copy and paste)

You must create a new string to put the encrypted text in outside of that for loop.

enc = ""

In order to encrypt the value by making a substitution you can add character one at a time to the encrypted string in that for loop if they are in the dictionary you defined. Something to the effect of

if (dtext[i] in CODE.keys()):
    enc += CODE[dtext[i]]

Then write the new string to a file and you're good to go.

A dictionary in python is effectively an array that is indexable by a key. This key maps to a given value just like an array index maps to some value. See https://www.tutorialspoint.com/python/python_dictionary.htm for more details.

1 Comment

Ahhh, I think I understand that! I will try and see if I can get it now. I was using this and started to get somewhere, but your method makes more sense. for line in dtext: for ch in line: print(ch, CODE[ch])
0

tdelaney's answer was correct, but I took it and made it a more simpler version. I changed it a bit. This is what I did:

Instead of joining to an empty string, I just removed that part completely. I just iterated over the entire string character by character and then as tdelaney did, used the get method to use the key in the code dictionary.

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

def main():
    #Open the file you want to encrypt.
    infile = str(input('Enter the name of the input file: '))
    #read its contents
    dtext = open(infile, 'r')
    #read the line from the file
    dtext = dtext.readlines()

    #call the encryptText function
    encryptText(dtext)

def encryptText(dtext):
    #enter the name of the file to write to
    outfile = str(input('Enter the name of the output file: '))
    #open the file to send encrypted text to
    etext = open(outfile, 'w')
    #create a for loop to read each separate character
    for line in dtext:
        # encrypt character by character then join to a string
        for c in line:
            encrypted = (CODE.get(c, c))
            etext.write(encrypted)
    #close the file
    etext.close()

main()

5 Comments

Just so you know, it's not convention to answer your own question. The last time i did, i was heavily downvoted and lost quite a bit of rep. I'm not going to do anything about it, b/c i think it makes sense. I thought i'd warn you though.
Oh really? Sorry, I'm new to all of this and this website. I appreciate the feedback though.
@thedevelop3r It's perfectly fine to answer your own question. You only need to understand that it needs to be a full answer to the question asked. That includes some code and a description of what was wrong. Also, copying somebody else's answer is also a no-go.
@Classicalclown Please try to be more careful about how you post code. I indented your code properly, but you will have to learn how to do it yourself like marking the code in question and hitting Ctrl+K. Also, you can edit your own answer. You don't have to delete an answer and post a new one.
Why was i down voted for answering my question on decreasing tripples then? Was it b/c i answered it as if i wasn't the ome who asked it? stackoverflow.com/q/36818054/3281844

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.