0

I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.

Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)

import re
text = input('Write Something- ')
word = '{}'.format(text)
for letter in word:
    print(letter)
    #lists down

Outcome-
Write something- test
t
e
s
t

Then I have this code that changes the letters into numbers, but I haven't been able to convert it back into letters. Code #2

u = input('Write Something')
a = ord(u[-1])
print(a)
#converts to number and prints ^^
enter code here
print('')
print(????)
#need to convert from numbers back to letters.

Outcome:
Write Something- test
116

How can I send a text through (test) and make it convert it to either set numbers (a->1, b->2) or random numbers, save it to a .txt file and be able to go back and read it at any time?

Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501
Jay
  • 11
  • 1
  • 6
  • This is far too broad, this isn't a code-writing or tutorial service. Also, if you swap with random numbers, how will you convert it back? – jonrsharpe Jul 20 '16 at 07:23
  • 1
    Why not use a dictionary to map specific numbers to each letter. Or do you want random numbers for each letter. Or do you want the ascii representation of each letter? – Steven Summers Jul 20 '16 at 07:24
  • It seems you're missing some basics. Why do you use `word = '{}'.format(text)`? – Matthias Jul 20 '16 at 07:36
  • I guess you can just map everything to a dictionary or list? You can have `for x in INPUT` then `NEWCHARACTER = DICTIONARY[x]` and then append a the new character to some other place like `NEWSTRING = NEWSTRING + NEWCHARACTER` – Luke Jul 20 '16 at 10:30

4 Answers4

0

Just use dictionary:

 letters = {'a': 1, 'b': 2, ... }

And in the loop:

for letter in word:
    print(letters[letter])
PatNowak
  • 5,721
  • 1
  • 25
  • 31
0

What youre trying to achieve here is called "caesar encryption".

You for example say normally you would have: A=1, a=2, B=3, B=4, etc...

then you would have a "key" which "shifts" the letters. Lets say the key is "3", so you would shift all letters 3 numbers up and you would end up with: A=4, a=5, B=6, b=7, etc...

This is of course only ONE way of doing a caesar encryption. This is the most basic example. You could also say your key is "G", which would give you:

A=G, a=g, B=H, b=h, etc.. or
A=G, a=H, B=I, b=J, etc...

Hope you understand what im talking about. Again, this is only one very simple example way.

Now, for your program/script you need to define this key. And if the key should be variable, you need to save it somewhere (write it down). Put your words in a string, and check and convert each letter and write it into a new string.

You then could say (pseudo code!):

var key = READKEYFROMFILE;
string old = READKEYFROMFILE_OR_JUST_A_NORMAL_STRING_:)
string new = "";

for (int i=0, i<old.length, i++){
get the string at i;
compare with your "key";
shift it;
write it in new;
}

Hope i could help you.

edit:

You could also use a dictionary (like the other answer says), but this is a very static (but easy) way.

Also, maybe watch some guides/tutorials on programming. You dont seem to be that experienced. And also, google "Caesar encryption" to understand this topic better (its very interesting).

edit2:

Ok, so basically:

You have a variable, called "key" in this variable, you store your key (you understood what i wrote above with the key and stuff?)

You then have a string variable, called "old". And another one called "new".

In old, you write your string that you want to convert. New will be empty for now.

You then do a "for loop", which goes as long as the ".length" of your "old" string. (that means if your sentence has 15 letters, the loop will go through itself 15 times and always count the little "i" variable (from the for loop) up).

You then need to try and get the letter from "old" (and save it for short in another vairable, for example char temp = "" ).

After this, you need to compare your current letter and decide how to shift it. If thats done, just add your converted letter to the "new" string.

Here is some more precise pseudo code (its not python code, i dont know python well), btw char stands for "character" (letter):

var key = g;
string old =  "teststring";
string new = "";
char oldchar = "";
char newchar = "";

for (int i=0; i<old.length; i++){
oldchar = old.charAt[i];
newchar = oldchar //shift here!!!
new.addChar(newchar);
}

Hope i could help you ;)

edit3:

maybe also take a look at this:

https://inventwithpython.com/chapter14.html

Caesar Cipher Function in Python

https://www.youtube.com/watch?v=WXIHuQU6Vrs

Community
  • 1
  • 1
Reaper
  • 740
  • 1
  • 7
  • 18
  • hey, i tried usig your code but i dont understand it alot. By any chance could you state a example and what each does? Thanks :) – Jay Jul 20 '16 at 07:38
0

To convert to symbol codes and back to characters:

text = input('Write Something')
for t in text:
    d = ord(t)
    n = chr(d)

    print(t,d,n)

To write into file:

f = open("a.txt", "w")
f.write("someline\n")
f.close()

To read lines from file:

f = open("a.txt", "r")
lines = f.readlines()

for line in lines:
    print(line, end='')  # all lines have newline character at the end

f.close()

Please see documentation for Python 3: https://docs.python.org/3/

akarilimano
  • 1,034
  • 1
  • 10
  • 17
0

Here are a couple of examples. My method involves mapping the character to the string representation of an integer padded with zeros so it's 3 characters long using str.zfill.

Eg 0 -> '000', 42 -> '042', 125 -> '125'

This makes it much easier to convert a string of numbers back to characters since it will be in lots of 3

Examples

from string import printable
#'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
from random import sample

# Option 1
char_to_num_dict = {key : str(val).zfill(3) for key, val in zip(printable, sample(range(1000), len(printable))) }

# Option 2
char_to_num_dict = {key : str(val).zfill(3) for key, val in zip(printable, range(len(printable))) }

# Reverse mapping - applies to both options
num_to_char_dict = {char_to_num_dict[key] : key for key in char_to_num_dict }

Here are two sets of dictionaries to map a character to a number. The first option uses random numbers eg 'a' = '042', 'b' = '756', 'c' = '000' the problem with this is you can use it one time, close the program and then the next time the mapping will most definitely not match. If you want to use random values then you will need to save the dictionary to a file so you can open to get the key.

The second option creates a dictionary mapping a character to a number and maintains order. So it will follow the sequence eg 'a' = '010', 'b' = '011', 'c' = '012' everytime.

Now I've explained the mapping choices here are the function to convert between

def text_to_num(s):
    return ''.join( char_to_num_dict.get(char, '') for char in s )

def num_to_text(s):
    slices = [ s[ i : i + 3 ] for i in range(0, len(s), 3) ]
    return ''.join( num_to_char_dict.get(char, '') for char in slices )

Example of use ( with option 2 dictionary )

>>> text_to_num('Hello World!')
'043014021021024094058024027021013062'
>>> num_to_text('043014021021024094058024027021013062')
'Hello World!'

And finally if you don't want to use a dictionary then you can use ord and chr still keeping with padding out the number with zeros method

def text_to_num2(s):
    return ''.join( str(ord(char)).zfill(3) for char in s )

def num_to_text2(s):
    slices = [ s[ i : i + 3] for i in range(0, len(s), 3) ]
    return ''.join( chr(int(val)) for val in slices )

Example of use

>>> text_to_num2('Hello World!')
'072101108108111032087111114108100033'
>>> num_to_text2('072101108108111032087111114108100033')
'Hello World!'
Steven Summers
  • 5,079
  • 2
  • 20
  • 31
  • Hey, i really like option 2, but the code isnt working for some reason. Ive changed it around abit to see if it works but it still isnt. Could you go through what each bit is and put up an example? Thanks :) – Jay Jul 20 '16 at 09:24
  • Could you explain how it isn't working? Any error? print the dictionary out and see if it looks okay. – Steven Summers Jul 20 '16 at 10:42