I would like to open a file with an encrypted message in it, eg a passage from a book.
4,5,4,3,1,1,2,3,4,5
to index each row. The result should be something like:
was h er
thise e
fret l
rj l
d o
This is what I have so far:
def cipher():
f = open("cipher.txt", "r")
fileString = f.readline()
for line in fileString:
lineSplit = line.split()
Some of your indexes are off by one, so I've corrected them to: 3,5,4,2,1,1,2,3,4,5
.
Below is the code you need, the problem was that you were only iterating through the lines and not extracting anything from them. Mostly because your function took no input.
This method takes a file-like object and an list of integers as a "key":
def cipher(encrypted,key):
return "".join([line[offset] for offset,line in zip(key,encrypted.readlines())])
Expanded out this is:
def cipher(encrypted,key):
message=[]
for offset,line in zip(key,encrypted.readlines()):
message.append(line[offset]
return "".join(message)
or building the string as you go (which might take longer as arrays are mutable, whereas this would require building a new string every iteration):
def cipher(encrypted,key):
message=""
for offset,line in zip(key,encrypted.readlines()):
message = message + line[offset]
return message
This takes the key and encrypted files and zip
s them together to make an accessible tuple, which we use to index into each line of the file. If the file could be quite long, you might want to use izip
from itertools
to zip using iterable instead of lists in memory.
And returns the text.
Here is an example program that calls it:
from StringIO import StringIO
f = StringIO("""washer
thisee
fretl
rjl
do""")
print cipher(f,[3,5,4,2,1,1,2,3,4,5])
And when run prints:
>>> hello
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.