
上圖是用了如下的表格
"qzirajsbktcludmvenwfoxgpyh" |
對以下的字串 (string) 而言
"There is no spoon." |
我們來想一想程式應該如何完成這一項工作,首先, 'T' 不是英文小寫字母,因此跳過,然後 'h' 、 'e' 、 'r' 、 'e' 都是英文小寫字母,對照表格,需要轉換為 'b' 、 'a' 、 'n' 、 'a' ,接下來遇到一個空格字元 ' ' ,也跳過,然後 'i' 、 's' 也都是英文小寫字母,需要轉換為 'k' 、 'w' ,餘下類推。
所以需要利用一個迴圈 (loop) 進行上述編碼工作,逐一檢查字串中的每一個元素,若是該元素為英文小寫字母,就開始進行編碼轉換,這是利用另外一個迴圈,檢查該元素於 self.alph 中的索引值,最後利用該索引值取出 self.code 裡的元素。
這是說,第 0 個字元(索引值為 0 ) 'T' 不在英文小寫字母編碼的範圍,因此程式不會處理,然後到第 1 個字母 'h' ,這在 self.alph 中索引值為 7 ,對照為 self.code 的 'b' ,因此 'h' 會轉換為 'b' 。
因此,編碼方法 (method) 設計如下
def toEncode( self , s): result = "" for i in s: if i in self .code: j = self .alph.index(i) result + = self .code[j] else : result + = i return result |
我們替 toEncode() 加上一個 s ,同樣預期這會是個字串,同時也是要進行編碼的字串, result 則是暫存編碼結果的空字串。
編碼過程很簡單,就在一個 for 迴圈中進行,逐一取得 s 中的元素,也就是單一字元的子字串,先判斷該子字串是否為英文小寫字母,如果是,就利用 index 方法找出在 self.alph 中索引值,然後依索引值取得在 self.code 的元素,最後 += 將該元素加入 result 的最後。
當然,如果 s 的元素不是英文小寫字母,就直接將該元素直接加入 result 的最後。解碼 (decoding) 其實跟編碼很雷同,只需要把 self.code 與 self.alph 的位置對調就可以了,如下
def toDecode( self , s): result = "" for i in s: if i in self .code: j = self .code.index(i) result + = self .alph[j] else : result + = i return result |
修改後的完整 encrypt.py 如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import random class Encrypt: def __init__( self ): self .code = [ chr (i) for i in range ( 97 , 123 )] random.shuffle( self .code) self .alph = [ chr (i) for i in range ( 97 , 123 )] def __str__( self ): return "code: " + "".join( self .code) def setCode( self , data): self .code = list (data) def getCode( self ): return "".join( self .code) def toEncode( self , s): result = "" for i in s: if i in self .code: j = self .alph.index(i) result + = self .code[j] else : result + = i return result def toDecode( self , s): result = "" for i in s: if i in self .code: j = self .code.index(i) result + = self .alph[j] else : result + = i return result if __name__ = = '__main__' : e = Encrypt() print () print (e) s1 = "There is no spoon." print ( "input: " + s1) s2 = e.toEncode(s1) print ( "encode: " + s2) s3 = e.toDecode(s2) print ( "decode: " + s3) print () # 《程式語言教學誌》的範例程式 # 檔名:encrypt.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2012 年 12 月 |
測試程式的部份我們也做了相對應的調整,執行結果如下

It's work!
好了,正式進入 GUI 的部份之前,先來認識標準模組庫及 Tk 吧!
中英文術語對照 | |
---|---|
編碼 | encoding |
串列 | list |
字串 | string |
迴圈 | loop |
方法 | method |
解碼 | decoding |
您可以繼續參考
軟體開發
相關目錄
回 Python 入門指南
回 Python 教材
回首頁
參考資料
http://docs.python.org/3.1/tutorial/classes.html
沒有留言:
張貼留言