2012-11-21 49 views
-3

我們將爲26個可能的密鑰中的每一個生成解密字母。Python凱撒休息時間

我已經完成了該部分,但無法打印出字典中的單詞。 例如:我只想'ebv'打印嘿

如何將它匹配到詞典中的單詞而不是打印出所有26個可能的鍵。

這裏的字典:http://www.ics.uci.edu/~kay/wordlist.txt

Alphabet = 'abcdefghijklmnopqrstuvwxyz' 

def rotated_alphabet(key:int) -> str: 
    '''produces a rotated alphabet based on key and adds those letters to the end of alphabet''' 
    if key > 26: 
     key = key % 26 
    new_alphabet = '' 
    w = Alphabet[0:key] 
    x = Alphabet.replace(Alphabet[0:key], new_alphabet) 
    return (x + w) 

def Caesar_break(cipher:str) ->str: 
    infile = open('wordlist.txt', 'r') 
    wordlist = [] 
    possible = [] 
    decode = [] 
    words = [] 
    for str in infile: 
     t = str 
    for i in range(0, 26): 
     p = rotated_alphabet(i).split() 
     possible+=p 
    for y in possible: 
     decrypt = str.maketrans(y, Alphabet) 
     decode.append(cipher.translate(decrypt)) 
    for str in decode: 
     s = str 
     words.append(s) 
    print(words) 

Caesar_break('eby') 

它打印出:

['ebv', 'dau', 'czt', 'bys', 'axr', 'zwq', 'yvp', 'xuo', 'wtn', 'vsm', 'url', 'tqk', 'spj', 'roi', 'qnh', 'pmg', 'olf', 'nke', 'mjd', 'lic', 'khb', 'jga', 'ifz', 'hey', 'gdx', 'fcw'] 
+0

**你有什麼** **?你卡在哪裏? –

+0

是'def Caesar_break(cipher:str) - > str:'有效的Python? –

+0

@hayden:是的,雖然在這裏不是很有用。參見[PEP 3107](http://www.python.org/dev/peps/pep-3107/#fundamentals-of-function- annotations)和[ref](http://docs.python.org/3.3 /reference/compound_stmts.html#function-definitions)。 – DSM

回答

1

的canoncial的方法來解決,這是:

  1. 閱讀從單詞列表,並插入所有行他們成字典dict
  2. 嘗試通過translate
  3. 各種凱撒旋轉。如果旋轉從字典(decrypt in dictionary)產生一個字,其輸出

對於較長的文本,你可能要檢查是否如至少有一半的單詞是在字典中找到的。注意小寫/大寫問題和換行等字符! - 嘗試使用strip

更高級的方法可以進行角色統計,並根據此統計量猜測正確的旋轉角度。