簡體   English   中英

Python中的凱撒密碼求解器

[英]Caesar Cipher solver in Python

我在 python 中做了一個凱撒密碼求解器,但沒有錯誤,只是沒有打印任何東西。 我也做過類似的事情,但以前沒有發生過這種情況。

with open("C:\\Users\\Rajive\\AppData\\Local\\Programs\\Python\\Python3.4.3\\brit-a-z.txt", 'r') as f:
    check_list = [x.strip() for x in f.readlines()]

def crackcaesar(encrypted):
    for i in range(26):
        totalwords = 0
        numright = 0
        answer = []
        if i != 0: 
            for symbol in encrypted:
                if symbol.isalpha():
                    neword = (ord(symbol) + i)
                    if symbol.isupper():
                            if neword > ord('Z'):
                                neword -= 26
                            elif neword < ord('A'):
                                neword += 26
                    elif symbol.islower():
                         if neword > ord('z'):
                             neword -= 26
                         elif neword < ord('a'):
                             neword += 26
                    newletter = chr(neword)
                    answer.append(newletter)
                    for word in str(answer):
                        totalwords += 1
                        for line in check_list:
                            if line == word:
                                numright += 1
        if (numright // 2) > (totalwords // 2):
            print(str(answer))

print("Type your encoded caesar cipher message")
while True:
    crackcaesar(input())

問題是, numright永遠不會大於totalwords 嘗試

if numright == totalwords:
    print(str(answer))

此外, answer是一個字符列表。 str(answer)會給你"['a', 'b', 'c']" 您需要使用"".join(answer)

首先,您有一個 3 級嵌套循環,實際上並未實現密碼。 其次,您沒有密鑰(請參閱下面的編輯)。 這個 for 循環:

for word in str(answer):
                        totalwords += 1
                        for line in check_list:
                            if line == word:
                                numright =+ 1

不應嵌套在這個已經嵌套的 for 循環中:

 for i in range(26):
        totalwords = 0
        numright = 0
        answer = []
        if i != 0: 
            for symbol in encrypted:

此外, if i != 0:i0-250-25的循環內部似乎沒有意義。 您似乎正在嘗試匹配字母范圍,但是如果您將范圍限制在 0-26 之間,那么實施 Caeser 密碼將不會有太多運氣,因為第一個可打印字符從 32(空格)和小寫'z'是 122。您應該一起刪除該循環- 它會破壞密碼。 只需for symbol in encrypted:循環中使用for symbol in encrypted:

此外, for word in str(answer):循環正在逐個字符地評估answer ,因此名為totalwords的變量實際上是在計算字符數,您只需獲取字符串的長度即可。 如果您嘗試做單詞,則應該在answer變量上調用str.split(' ') ,假設space字符是分隔字符。 希望這可以幫助。

編輯

你的鑰匙在哪里? (確切地)。 您的密碼的主要問題是當您需要添加(或減去)密鑰數量時,您要為每個序數值添加一個計數器變量。 由於您沒有實現密鑰轉換,因此您只需要添加一個值,否則您可以使用一組密鑰來實現 caeser 密碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM