问题描述
我一直在学校学习python,因此我决定完成一个制作解密器的任务,但与其输入更改消息的数量,不如输入消息的数量,它会检查每个单词并寻找常用单词并选择最可能的解密方法。如果不是您想要的,那么他们可以看着每一个人。但是我在获取代码解密每个数量时遇到了问题。这是部分代码返回奇数后返回的错误:IndexError:字符串索引超出范围。我不明白为什么它不起作用。这是我所知道的唯一编程语言,因此可能很明显,但我没有理解。我一直无法在线找到答案,所以如果有人找到解决方案,我将非常感激。预先感谢。
import sys
import time
from time import sleep as s
import random
import collections
LETTERS = 'ABCDEFGHIJKLMnopQRSTUVWXYZABCDEFGHIJKLMnopQRSTUVWXYZ'
LETTERS = LETTERS.lower()
global c1,message
c1=int(0)
message = input("Enter the thing you want to decrypt. ")
def decrypt():
global c1,LETTERS,message
decrypted = ''
for counter in range(1,27):
for chars in message:
if chars in LETTERS:
c1 = int(c1+counter)
num = LETTERS.find(chars)
num -= c1
decrypted += LETTERS[num]
s(1)
print(decrypted)
decrypt()
完整错误:
Enter the thing you want to decrypt. ij
hh
hhed
hhedzx
hhedzxsp
hhedzxspjf
hhedzxspjfyt
hhedzxspjfytlf
Traceback (most recent call last):
File "C:\Users\TomHu\Documents\Documents\Tom\School\Homework\Year 8\Computing\Python\Encrypter.py",line 30,in <module>
decrypt()
File "C:\Users\TomHu\Documents\Documents\Tom\School\Homework\Year 8\Computing\Python\Encrypter.py",line 25,in decrypt
decrypted += LETTERS[num]
IndexError: string index out of range
解决方法
您的示例中字母的长度为52。
可以与LETTERS(num)一起使用的索引必须在-52到51之间。但是,在出现错误之前,示例num等于-56。
您可以在print(num)
之前添加decrypted += LETTERS[num]
来查看它。
如果您想避免此问题,可以对len(LETTERS)取模:
import sys
import time
from time import sleep as s
import random
import collections
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS = LETTERS.lower()
length=len(LETTERS)
global c1,message
c1=int(0)
message = input("Enter the thing you want to decrypt. ")
def decrypt():
global c1,LETTERS,message
decrypted = ''
for counter in range(1,27):
for chars in message:
if chars in LETTERS:
c1 = int(c1+counter)
num = LETTERS.find(chars)
num -= c1
num=num%length
decrypted += LETTERS[num]
s(1)
print(decrypted)
decrypt()
使用此修改,您可以确保始终提供有效的索引。之后,您可以自由地修改算法以具有期望的输出。