Created
November 17, 2008 19:14
-
-
Save gvx/25866 to your computer and use it in GitHub Desktop.
Decode ROT13'ed block of text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ROTurn | |
#Decode a ROT13'ed block of text. | |
#Python version of Perl script by Jay Kominek | |
#By Robin Wellner (gvx) | |
#I hereby waive copyright and related or neighboring rights to this work | |
#See the Creative Commons Zero Waiver at <http://creativecommons.org/publicdomain/zero/1.0/> | |
""" | |
"I recently wrote a Perl script, which, using letter frequency, attempts | |
to guess whether a given block of text has been ROT13ed or not. I've found | |
that it works rather well (in my limited and very unscientific testing). | |
The basis is that in plaintext, the letters i, s, e and t are very frequent, | |
while their ROT13ed counterparts, v, f, r and g are relatively infrequent. | |
However, in ROT13ed text, this is reversed. Hence by comparing which set | |
of letters is predominant, you can make an awfully good guess as to which | |
type of text you are dealing with." | |
-- Jay Kominek (http://www.miranda.org/~jkominek/rot13/) | |
""" | |
def rotn(intext, n): | |
outtext = [] | |
for char in intext: | |
if 65 <= ord(char) < (65+26): | |
char = chr(((ord(char) - 65) +n) % 26 + 65) | |
elif 97 <= ord(char) < (97+26): | |
char = chr(((ord(char) - 97) +n) % 26 + 97) | |
outtext.append(char) | |
return ''.join(outtext) | |
def rot13(intext): | |
return rotn(intext, 13) | |
def rot_predict(intext): | |
"""Returns True if probably ROT13'ed, else False.""" | |
score = ( intext.count('i') | |
+intext.count('s') | |
+intext.count('e') | |
+intext.count('t') | |
-intext.count('v') | |
-intext.count('f') | |
-intext.count('r') | |
-intext.count('g')) | |
return score < 0 | |
def roturn(intext): | |
"""Fixes ROT13'ed text, returns normal text untouched.""" | |
if rot_predict(intext): | |
return rot13(intext) | |
return intext |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment