# 【wk15_1214】_期末專題參考 <pre> {實戰#5} : 凱薩密碼加密/解密 {實戰#6} : line貼圖收集器 【oneDrive】課程資源 (密碼 : 1121python)/00_Python大數據特訓班(第二版)/教學影片/videos/ch07/ <pre/> # 凱薩密碼 參考文件: https://github.com/CrypTools/CaesarCipher ```python import string import matplotlib.pyplot as plt LETTERS = 'abcdefghijklmnopqrstuvwxyz,.() ' def encrypt(initial, shift): initial = initial.lower() output = "" for char in initial: if char in LETTERS: output += LETTERS[(LETTERS.index(char) + shift) % len(LETTERS)] return output def decrypt(initial, shift): initial = initial.lower() output = "" for char in initial: if char in LETTERS: output += LETTERS[(LETTERS.index(char) - shift) % len(LETTERS)] return output def plot_letter_frequency(text): text = text.lower() letter_count = {letter: 0 for letter in string.ascii_lowercase} for char in text: if char.isalpha(): letter_count[char] += 1 letters = list(letter_count.keys()) counts = list(letter_count.values()) plt.bar(letters, counts) plt.xlabel('Letters') plt.ylabel('Frequency') plt.title('Letter Frequency in Text') plt.savefig('./result.png') ## --------------- Main ------------------ message = input('請輸入要加密的訊息: ') key = int(input('請輸入密鑰: ')) # 加密 cipher = encrypt(message, key) print(f'\n加密結果: {cipher}') # 解密 plain = decrypt(cipher, key) print(f'\n解密結果: {plain}') #字數統計 plot_letter_frequency(cipher) ``` 請輸入要加密的訊息: “Here in New South Wales, we’ve just seen the crushing of the convictions of Kathleen Folbigg after 20 years in jail. If a case of this magnitude does not trigger law reform, I’m not sure what does,” she said. “It is time for Australia to review its legal system to ensure it can be more scientifically informed, particularly given the pace of change of scientific discovery and technological advances.” 請輸入密鑰: 8 加密結果: pmzmhqvhvm h,w(.ph itm,dh m)mhr(,.h,mmvh.pmhkz(,pqvohwnh.pmhkwv)qk.qwv,hwnhsi.ptmmvhnwtjqoohin.mzhhbmiz,hqvhriqtehqnhihki,mhwnh.pq,huiovq.(lmhlwm,hvw.h.zqoomzhti hzmnwzudhquhvw.h,(zmh pi.hlwm,dh,pmh,iqlehhq.hq,h.qumhnwzhi(,.zitqih.whzm)qm hq.,htmoith,b,.muh.whmv,(zmhq.hkivhjmhuwzmh,kqmv.qnqkittbhqvnwzumldhxiz.qk(tiztbhoq)mvh.pmhxikmhwnhkpivomhwnh,kqmv.qnqkhlq,kw)mzbhivlh.mkpvwtwoqkithil)ivkm,e 解密結果: here in new south wales, weve just seen the crushing of the convictions of kathleen folbigg after years in jail. if a case of this magnitude does not trigger law reform, im not sure what does, she said. it is time for australia to review its legal system to ensure it can be more scientifically informed, particularly given the pace of change of scientific discovery and technological advances. ![png](output_2_1.png) ![output_2_1](https://hackmd.io/_uploads/HJNRhTOLp.png)