ccmny

Letter Stats Decipher

Jun 24th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. from operator import itemgetter
  2. import urllib
  3.  
  4. def getStats(string):
  5.     letters = [chr(i) for i in xrange(0,256)]
  6.     output = {}
  7.    
  8.     string = string.lower()
  9.     string = string.replace(" ", "").replace(".", "").replace(",","")
  10.     string = string.replace("\n","").replace("\r","")
  11.    
  12.     for letter in letters:
  13.         count = string.count(letter)
  14.         if count > 0 and ord(letter) >= ord('a') and ord(letter) <= ord('z'):
  15.             output[letter] = float(count)/len(string) * 100
  16.     return output
  17.  
  18. def decipher(statsStr, cipherStr):
  19.     statsStr = statsStr.lower()
  20.     cipherStr = cipherStr.lower()
  21.        
  22.     stats = sorted(getStats(statsStr).items(), key=itemgetter(1))
  23.     stats = convertList(stats)
  24.     cipher = sorted(getStats(cipherStr).items(), key=itemgetter(1))
  25.     cipher = convertList(cipher)
  26.    
  27.     cipherList = list(cipherStr)
  28.     outputList = list(cipherStr)
  29.    
  30.     for i in xrange(0, len(stats)):
  31.         outputList = listReplace(outputList, cipherList, cipher[i], stats[i])
  32.     return "".join(outputList)
  33.  
  34. def convertList(list):
  35.     return  [item[0] for item in list]
  36.  
  37. def listReplace(output, input, replaced, replacing):
  38.     for i in xrange(0, len(input)):
  39.         if input[i] == replaced:
  40.             output[i] = replacing
  41.     return output
  42.    
  43. def main():
  44.     string = urllib.urlopen("http://home.agh.edu.pl/~kanczula/kryptografia/lab/lab02/text.txt").read()
  45.     cipher = urllib.urlopen("http://home.agh.edu.pl/~kanczula/kryptografia/lab/lab02/szyfrogram.txt").read()
  46.     print decipher(string, cipher)
  47.    
  48. if __name__ == "__main__":
  49.     main()
Advertisement
Add Comment
Please, Sign In to add comment