from letprob import *
class Cipher(object):
def __init__(self, inputString):
self.inputString = inputString
self.encodedString = ''
self.decodedString = ''
def __repr__(self):
s = 'Original String: %s\nEncoded String: %s\nDecoded String: %s' \
% (self.inputString, self.encodedString, self.decodedString)
return s
def encipher(self, n):
for i in (self.inputString):
if 'a' <= i <= 'z':
encWord = (ord(i) + n - 97) % 26 + 97
encWord1 = chr(encWord)
self.encodedString += encWord1
elif 'A' <= i <= 'Z':
newWord = (ord(i) + n - 65) % 26 + 65
newWord1 = chr(newWord)
self.encodedString += newWord1
else:
self.encodedString += i
def decipherEasy(self, n):
for i in (self.encodedString):
if 'a' <= i <= 'z':
decWord = (ord(i) - n - 97) % 26 + 97
decWord1 = chr(decWord)
self.decodedString += decWord1
elif 'A' <= i <= 'Z':
newWordD = (ord(i) - n - 65) % 26 + 65
newWord1D = chr(newWordD)
self.decodedString += newWord1D
else:
self.decodedString += i
def shift(self, encodedString, n):
decodedString = ''
for i in (encodedString):
if 'a' <= i <= 'z':
decWord = (ord(i) + n - 97) % 26 + 97
decWord1 = chr(decWord)
decodedString += decWord1
elif 'A' <= i <= 'Z':
newWordD = (ord(i) + n - 65) % 26 + 65
newWord1D = chr(newWordD)
decodedString += newWord1D
else:
decodedString += i
return decodedString
def decipher(self):
shiftList = []
score = 0
for i in range(0, 26+1):
shiftStr = self.shift(self.encodedString, i)
prob = self.possibleProb(shiftStr)
shiftList.append([shiftStr, prob])
self.sortProb(shiftList)
#print(shiftList)
#return shiftList
def sortProb(self, List):
size = len(self.shiftList)
for i in range(size):
for j in range(1, size):
if List[j][1] > List[j - 1][1]:
print(j)
temp = List[j]
List[j] = List[j - 1]
List[j-1] = temp
else:
return List
def possibleProb(self, sentence):
s = 0
for i in sentence:
s += letProb(i)
return s
def main():
cipher = Cipher('this')
cipher.encipher(1)
# cipher.decipherEasy(1)
cipher.decipher()
print(cipher)
if __name__ == '__main__':
main()
获取
Traceback (most recent call last):
main()
NameError: name 'main' is not defined
有人会帮助我运行此代码吗? 尝试了所有没有用的东西 无法运行该程序,它显示此错误?
答案 0 :(得分:1)
在调试此类问题时,它有助于删除所有不相关的内容,并简化为仍会产生相同错误的最小程序。由于程序几乎立即崩溃,因此几乎所有内容都可以执行。该脚本会产生相同的错误
class Cipher(object):
def main():
print("not fubar")
if __name__ == '__main__':
main()
问题很容易发现:main
不应成为课程的一部分。
class Cipher(object):
pass
def main():
print("not fubar")
if __name__ == '__main__':
main()
将该修补程序应用于实际程序,您将进入下一期。