0

I want to determine which type of ROT encoding is used and based off that, do the correct decode.

Also, I have found the following code which will indeed decode rot13 "sbbone" to "foobart" correctly:

import codecs
codecs.decode('sbbone', 'rot_13')

The thing is I'd like to run this python file against an existing file which has rot13 encoding. (for example rot13.py encoded.txt).

Thank you!

4

2 回答 2

1

要回答第一个问题的第二部分,解码中的ROT-x内容,您可以使用以下代码:

def encode(s, ROT_number=13):
    """Encodes a string (s) using ROT (ROT_number) encoding."""
    ROT_number %= 26  # To avoid IndexErrors
    alpha = "abcdefghijklmnopqrstuvwxyz" * 2
    alpha += alpha.upper()
    def get_i():
        for i in range(26):
            yield i  # indexes of the lowercase letters
        for i in range(53, 78):
            yield i  # indexes of the uppercase letters
    ROT = {alpha[i]: alpha[i + ROT_number] for i in get_i()}
    return "".join(ROT.get(i, i) for i in s)


def decode(s, ROT_number=13):
    """Decodes a string (s) using ROT (ROT_number) encoding."""
    return encrypt(s, abs(ROT_number % 26 - 26))

要回答第一个问题的第一部分,找到任意编码字符串的 rot 编码,您可能想要蛮力。使用所有的 rot 编码,并检查哪一种最有意义。一种快速(-ish)的方法是获取一个以空格分隔(例如,换行符cat\ndog\nmouse\nsheep\nsay\nsaid\nquick\n...在哪里\n)的文件,其中包含英语中最常见的单词,然后检查哪个编码中的单词最多。

with open("words.txt") as f:
    words = frozenset(f.read().lower().split("\n"))
    # frozenset for speed
def get_most_likely_encoding(s, delimiter=" "):
    alpha = "abcdefghijklmnopqrstuvwxyz" + delimiter
    for punctuation in "\n\t,:; .()":
        s.replace(punctuation, delimiter)
    s = "".join(c for c in s if c.lower() in alpha)
    word_count = [sum(w.lower() in words for w in encode(
            s, enc).split(delimiter)) for enc in range(26)]
    return word_count.index(max(word_count))

您可以在 Unix 机器上使用的文件是/usr/dict/words,也可以在此处找到

于 2015-02-16T16:00:11.310 回答
0

好吧,您可以逐行读取文件并对其进行解码。输出应转到输出文件:

import codecs
import sys


def main(filename):
    output_file = open('output_file.txt', 'w')
    with open(filename) as f:
        for line in f:
            output_file.write(codecs.decode(line, 'rot_13')) 
    output_file.close()

if __name__ == "__main__":
    _filename = sys.argv[1]
    main(_filename)
于 2015-02-16T15:21:52.293 回答