rot_13.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #!/usr/bin/env python
  2. """ Python Character Mapping Codec for ROT13.
  3. This codec de/encodes from str to str.
  4. Written by Marc-Andre Lemburg (mal@lemburg.com).
  5. """
  6. import codecs
  7. ### Codec APIs
  8. class Codec(codecs.Codec):
  9. def encode(self, input, errors='strict'):
  10. return (str.translate(input, rot13_map), len(input))
  11. def decode(self, input, errors='strict'):
  12. return (str.translate(input, rot13_map), len(input))
  13. class IncrementalEncoder(codecs.IncrementalEncoder):
  14. def encode(self, input, final=False):
  15. return str.translate(input, rot13_map)
  16. class IncrementalDecoder(codecs.IncrementalDecoder):
  17. def decode(self, input, final=False):
  18. return str.translate(input, rot13_map)
  19. class StreamWriter(Codec,codecs.StreamWriter):
  20. pass
  21. class StreamReader(Codec,codecs.StreamReader):
  22. pass
  23. ### encodings module API
  24. def getregentry():
  25. return codecs.CodecInfo(
  26. name='rot-13',
  27. encode=Codec().encode,
  28. decode=Codec().decode,
  29. incrementalencoder=IncrementalEncoder,
  30. incrementaldecoder=IncrementalDecoder,
  31. streamwriter=StreamWriter,
  32. streamreader=StreamReader,
  33. _is_text_encoding=False,
  34. )
  35. ### Map
  36. rot13_map = codecs.make_identity_dict(range(256))
  37. rot13_map.update({
  38. 0x0041: 0x004e,
  39. 0x0042: 0x004f,
  40. 0x0043: 0x0050,
  41. 0x0044: 0x0051,
  42. 0x0045: 0x0052,
  43. 0x0046: 0x0053,
  44. 0x0047: 0x0054,
  45. 0x0048: 0x0055,
  46. 0x0049: 0x0056,
  47. 0x004a: 0x0057,
  48. 0x004b: 0x0058,
  49. 0x004c: 0x0059,
  50. 0x004d: 0x005a,
  51. 0x004e: 0x0041,
  52. 0x004f: 0x0042,
  53. 0x0050: 0x0043,
  54. 0x0051: 0x0044,
  55. 0x0052: 0x0045,
  56. 0x0053: 0x0046,
  57. 0x0054: 0x0047,
  58. 0x0055: 0x0048,
  59. 0x0056: 0x0049,
  60. 0x0057: 0x004a,
  61. 0x0058: 0x004b,
  62. 0x0059: 0x004c,
  63. 0x005a: 0x004d,
  64. 0x0061: 0x006e,
  65. 0x0062: 0x006f,
  66. 0x0063: 0x0070,
  67. 0x0064: 0x0071,
  68. 0x0065: 0x0072,
  69. 0x0066: 0x0073,
  70. 0x0067: 0x0074,
  71. 0x0068: 0x0075,
  72. 0x0069: 0x0076,
  73. 0x006a: 0x0077,
  74. 0x006b: 0x0078,
  75. 0x006c: 0x0079,
  76. 0x006d: 0x007a,
  77. 0x006e: 0x0061,
  78. 0x006f: 0x0062,
  79. 0x0070: 0x0063,
  80. 0x0071: 0x0064,
  81. 0x0072: 0x0065,
  82. 0x0073: 0x0066,
  83. 0x0074: 0x0067,
  84. 0x0075: 0x0068,
  85. 0x0076: 0x0069,
  86. 0x0077: 0x006a,
  87. 0x0078: 0x006b,
  88. 0x0079: 0x006c,
  89. 0x007a: 0x006d,
  90. })
  91. ### Filter API
  92. def rot13(infile, outfile):
  93. outfile.write(codecs.encode(infile.read(), 'rot-13'))
  94. if __name__ == '__main__':
  95. import sys
  96. rot13(sys.stdin, sys.stdout)