al = 'a ą b c ć d e ę f g h i j k l ł m n ń o ó p r s ś t u w y z ź ż'.split() def decoder(char, key): upper = char.isupper() try: outchar=key[char.lower()] except KeyError: outchar = char if upper: outchar = outchar.upper() return outchar def ranks(f): frequencies = {} for line in f: for char in line: if not char.lower() in al: continue if char.lower() in frequencies: frequencies[char.lower()] += 1 else: frequencies[char.lower()] = 1 return sorted([(i[1], i[0]) for i in frequencies.items()], reverse=True) with open('pantad.TXT', encoding='utf8') as f: rankspl = ranks(f) with open('coded.txt', encoding='utf8') as coded: rankscoded = ranks(coded) keylen = min(len(rankspl), len(rankscoded)) rankscombined = zip(rankspl[:keylen], rankscoded[:keylen] ) key = dict([ (i[1][1], i[0][1], ) for i in rankscombined]) with open('decoded.txt','w', encoding='utf8') as fout: with open('coded.txt', encoding='utf8') as coded: for line in coded: decodedline = [] for char in line: decodedline.append(decoder(char, key)) fout.write(''.join(decodedline))