IndexError:字符串索引超出范围<制作加密,=“”decrypt =“”“program =”“>

时间:2016-06-01 02:43:05

标签: python

import random
#get filename
name = input('Enter filename: ')

#load file
try:
    input_file = open(name, 'r')
except IOError:
    print('File does not exist. Program will terminate.')

#make key value
line = input_file.readline()

key = []
key_mix = []

for i in range(len(line)):
    if line[i] not in key:
        key.append(line[i])
for i in range(len(line)):
    if line[i] not in key_mix:
        key_mix.append(line[i])

random.shuffle(key_mix)


#encryption
if name.split('.')[1] == 'txt':
    try:
        key_file = open(name.split('.')[0] + '.key', 'w')
        enc_file = open(name.split('.')[0] + '.enc', 'w')
    except IOError:
        print('File does not exist. Program will terminate.')

    key_write = ['']
    for g in range(len(key)):
        key_write[0] += key_mix[g]

    for i in range(len(key)):
        keys = str(key[i]) + ',' + str(key_mix[i])
        key_file.write(keys+'\n')

    couple = {}

    for k in range(len(key)):
        couple[key[k]] = key_mix[k]


    enc = ['']

    for t in range(len(line)):
        enc[0] += couple.get(line[t])

    enc_file.write(enc[0])
    input_file.close()
    key_file.close()
    enc_file.close()

#decryption
elif name.split('.')[1] == 'enc':
    try:
        key_file = open(name.split('.')[0] + '.key', 'r')
        dec_file = open(name.split('.')[0] + '.txt', 'w')
    except IOError:
        print('File does not exist. Program will terminate.')
    line = input_file.readline()

    dec = ['']
    sol = {}
    while True:
        sen = key_file.readline()
        if not sen: break
        sol.update({sen[2]:sen[0]})*Problem Here*

    for m in range(len(line)):
        dec[0] += sol.get(line[m])


    dec_file.write(dec[0])
    input_file.close()
    key_file.close()
    dec_file.close()

它出错:

  

IndexError:字符串索引超出范围

当我查看我的.key文件时,它就像

t,o
h,l
e,s
r,h
i,t
s,r
 ,n
n,v
o,u
u,e
f,i
l,f
v, 

但是当我打印readline时,它就像

t,o
(blank)
e,s
(blank)
i,t
(blank)
,n
(blank)
o,u
(blank)
f,i
(blank)
v, 
(blank)

我该如何解决?

0 个答案:

没有答案