<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>
追踪(最近一次通话): 文件&#34; C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ Rot14.py&#34;,第61行,in 主要() 文件&#34; C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ Rot14.py&#34;,第18行,主要 content = file.readlines() 读取线中的文件&#34; C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ codecs.py&#34;,第706行 return self.reader.readlines(sizehint) 文件&#34; C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ codecs.py&#34;,第615行,在readlines data = self.read() 文件&#34; C:\ Users \ waldemar \ AppData \ Local \ Programs \ Python \ Python35-32 \ lib \ codecs.py&#34;,第501行,读取 newchars,decodingbytes = self.decode(data,self.errors) UnicodeDecodeError:&#39; utf-8&#39;编解码器不能解码位置28中的字节0xea:无效的连续字节
答案 0 :(得分:0)
输入文件不是UTF-8,或者content = file.readlines()
不会出错。
如果您将输入文件正确保存为UTF-8,则另一个错误是需要以UTF-8编写输出文件:
output = open(file_output,mode = 'w', encoding='utf8')
然后输出文件包含:
Od godziny zerowej mam wachtę na Morzu Lewantyńskim.
需要注意的另一件事是Python 3不需要codecs.open
。例如,输出文件只使用内置的Python 3 open
。