robert williams robert williams - 1 month ago 10
Python Question

printing the output for each line from a file in python

I want to print the encrypted version of each line read from the file /tmp/values.txt. Can anyone please help me with the logic? Below is my code:

with open ('/tmp/values.txt') as f:
sentence = f.readlines()
for sent in sentence:
crypt,key = [ x for x in sent.rstrip().split('|')]
key = key.strip().split(' ')
key = list(map(int , key))
new_keys = [ (x-1) for x in key]
op = [crypt[new_keys[keys]] for keys in range(0,len(new_keys))]
print (''.join(op))


/tmp/values.txt :

Ta1HN9UPlxLfsYzEIAR4GcJQvh5biMW7oun0S8Keq6tDZmkVjX3FgB2yCwrOd p| 18 9 40 10 2 35 61 40 59 62 8 34 13 26 47 29 35 62 3 32 6 6
7NZq8pegmhAnBKH4VrGQdbPFw35jaUCzOS10oyLiv6IMXJW2 ksDRTfucElYxt9| 47 40 59 59 40 29 9 49 34 10 29 50 7 51 6 7 29 18 7 49 35 27 42 16
6qcAdESB7tlep9suiyOv8zXFg24TkaZxKLbhRUMjC3GHrI5o 10QPmVJfYWDNnw| 34 12 63 17 15 49 41 30 45 45 48 11 11 49 50 21 42 26

Answer

I wasn't sure if lines in file start with two spaces or it is only mistake so I used strip() instead of rstrip() and now (with correct indentions) it works for me.

with open ('/tmp/values.txt') as f:
    sentence = f.readlines()
    for sent in sentence:
        crypt,key = [ x for x in sent.rstrip().split('|')]
        key = key.strip().split(' ')
        key = list(map(int , key))
        new_keys = [  (x-1)  for x in key]
        op = [crypt[new_keys[keys]] for keys in range(0,len(new_keys))]
        print (''.join(op))

For test I made this version using string instead of file:

data = '''  Ta1HN9UPlxLfsYzEIAR4GcJQvh5biMW7oun0S8Keq6tDZmkVjX3FgB2yCwrOd p| 18 9 40 10 2 35 61 40 59 62 8 34 13 26 47 29 35 62 3 32 6 6
  7NZq8pegmhAnBKH4VrGQdbPFw35jaUCzOS10oyLiv6IMXJW2 ksDRTfucElYxt9| 47 40 59 59 40 29 9 49 34 10 29 50 7 51 6 7 29 18 7 49 35 27 42 16
  6qcAdESB7tlep9suiyOv8zXFg24TkaZxKLbhRUMjC3GHrI5o 10QPmVJfYWDNnw| 34 12 63 17 15 49 41 30 45 45 48 11 11 49 50 21 42 26'''

for sent in data.split('\n'):
    crypt,key = [ x for x in sent.strip().split('|')]
    key = key.strip().split(' ')
    key = list(map(int , key))
    new_keys = [  (x-1)  for x in key]
    op = [crypt[new_keys[keys]] for keys in range(0,len(new_keys))]
    print (''.join(op))

After some small modifications I get:

data = '''  Ta1HN9UPlxLfsYzEIAR4GcJQvh5biMW7oun0S8Keq6tDZmkVjX3FgB2yCwrOd p| 18 9 40 10 2 35 61 40 59 62 8 34 13 26 47 29 35 62 3 32 6 6
  7NZq8pegmhAnBKH4VrGQdbPFw35jaUCzOS10oyLiv6IMXJW2 ksDRTfucElYxt9| 47 40 59 59 40 29 9 49 34 10 29 50 7 51 6 7 29 18 7 49 35 27 42 16
  6qcAdESB7tlep9suiyOv8zXFg24TkaZxKLbhRUMjC3GHrI5o 10QPmVJfYWDNnw| 34 12 63 17 15 49 41 30 45 45 48 11 11 49 50 21 42 26'''

for sent in data.split('\n'):
    crypt, keys = sent.strip().split('|')
    keys = keys.strip().split(' ')
    keys = [int(x)-1 for x in keys]
    op = [crypt[x] for x in keys]
    print(''.join(op))

Result:

Alexander Pushkin 1799
William Shakespeare 1564
Lewis Carroll 1832