<pre>import os, sys, codecs
from collections import defaultdict
letters = 'abcdefghijklmnopqrstuvwxyz'
bigLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def countLetters(file):
results = defaultdict(int)
for line in file:
for char in line:
if char.lower() in letters:
c = char.lower()
results[c] += 1
return results
def main():
file = codecs.open('szyfrogram.txt','r',encoding='utf-8')
content = file.readlines()
file.close()
dictionary = countLetters(content)
most_popular = (max(dictionary, key=dictionary.get))
shift_for_a = 122 - ord(most_popular.lower()) + 1
saveDecoded(content, shift_for_a,'results_decoded.txt')
def saveDecoded(encoded, shift,file_output):
decoded = ''
for line in encoded:
line = line.strip('\n')
for char in line:
decoded = decoded + move(char,shift)
output = open(filr_output,mode = 'w')
output.write(decoded)
output.close
def move(letter,shift):
moveletter = letter
if letter in letters:
lower_range = 96
top_range = 122
moveCharLetters = ord(letter) + shift
if moveCharLetters > top_range:
moveCharLetters = lower_range + moveCharLetters-top_range
moveletter = chr(moveCharLetters)
else:
moveletter = chr(moveCharLetters)
elif letter in bigLetters:
lower_range = 64
top_range = 90
moveCharLetters = ord(letter) + shift
if moveCharLetters > top_range:
moveCharLetters = lower_range + moveCharLetters-top_range
moveletter = chr(moveCharLetters)
else:
moveletter = chr(moveCharLetters)
else:
moveletter = letter
return moveletter
print('countLetters')
main()<code>
回溯(最近通話最後一個): 文件 「C:\用戶\瓦爾德馬\應用程序數據\本地\程序\ Python的\ Python35-32 \ Rot14.py」 61行,在 main() 文件「C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ Rot14.py」,第18行,主要內容爲 content = file.readlines() 文件「C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ codecs.py「,第706行,在readlines中 return self.reader.readlines(sizehint) 文件」C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ codecs.py「,第615行,在readlines中 data = self.read() 文件「C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ codecs.py」,第501行,在讀 newchars,decodedbytes = self.decode(data,self.errors) UnicodeDecodeError:'utf-8'編解碼器無法解碼位置28中的字節0xea:無效延續字節 如何修復錯誤
你可以在文章中包含你的代碼作爲文本(只需要縮進它的另外4個字符,這樣格式化程序使它成爲一個不錯的塊),而不是將它鏈接爲圖像。 –
在您的問題中包含代碼。 – zondo
你確定你的源文件是utf-8編碼,而不是拉丁文或其他? – antikantian