Decode Bacon\'s cipher


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import re
  2.  
  3. def bacon2text(bacon):
  4. """ This function converts a string in bacon (a lot of 'a's and 'b's) to
  5. plain text. The plaintext is returned. If a character can't be
  6. translated, a space will be inserted. """
  7.  
  8. bacondict = {}
  9. plaintext = ""
  10.  
  11. bacon = bacon.lower()
  12. bacon = re.sub("[\W\d]", "", bacon.strip())
  13. for i in xrange(0,26):
  14. tmp = bin(i)[2:].zfill(5)
  15. tmp = tmp.replace('0', 'a')
  16. tmp = tmp.replace('1', 'b')
  17. bacondict[tmp] = chr(65+i)
  18.  
  19. for i in xrange(0, len(bacon)/5):
  20. plaintext = plaintext + bacondict.get(bacon[i*5:i*5+5], ' ')
  21. return plaintext
  22.  
  23. crypto = """BAABBAABBBABAAABAABA ABAAABAABA AAAAA AAAABAAAAAAAABAABBBAABBAB AAABAABAAAABBBBAABBBAABAABAAAB ABBAAAABAABAABABAABAAAAAAAABBAAABAA"""
  24. print bacon2text(crypto)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.