rot.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/env python3
  2. """
  3. # rotate - Copyright (c) 2009-2022 Michael Buesch <m@bues.ch>
  4. # Licensed under the
  5. # GNU General Public license version 2 or (at your option) any later version
  6. """
  7. import sys
  8. import getopt
  9. def rotateChar(c, count):
  10. count %= 26
  11. c = ord(c)
  12. if c >= ord('a') and c <= ord('z'):
  13. start = ord('a')
  14. end = ord('z')
  15. elif c >= ord('A') and c <= ord('Z'):
  16. start = ord('A')
  17. end = ord('Z')
  18. else: # Do not rotate
  19. return chr(c)
  20. c += count
  21. if (c < start):
  22. c = end - (start - c - 1)
  23. elif (c > end):
  24. c = start + (c - end - 1)
  25. assert(c >= start and c <= end)
  26. return chr(c)
  27. def rotateString(string, count):
  28. s = ""
  29. for c in string:
  30. s += rotateChar(c, count)
  31. return s
  32. def test():
  33. count = 0
  34. for i in range(-100, 101):
  35. s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!@#$%^&*()_+|~"
  36. if (rotateString(rotateString(s, i), -i) != s):
  37. print("Selftest FAILED at", i)
  38. return 1
  39. count += 1
  40. print(count, "selftests passed")
  41. return 0
  42. def usage():
  43. print("Usage: %s [OPTIONS]" % sys.argv[0])
  44. print("")
  45. print("-h|--help Print this help text")
  46. print("-c|--count COUNT Rotate by COUNT")
  47. print("-s|--string STR Rotate STR (no prompt)")
  48. print("-f|--file FILE Rotate the contents of FILE")
  49. def main(argv):
  50. opt_count = 13
  51. opt_string = None
  52. opt_file = None
  53. try:
  54. (opts, args) = getopt.getopt(argv[1:],
  55. "hc:s:f:t",
  56. [ "help", "count=", "string=", "test", ])
  57. for (o, v) in opts:
  58. if o in ("-h", "--help"):
  59. usage()
  60. return 0
  61. if o in ("-c", "--count"):
  62. opt_count = int(v)
  63. if o in ("-s", "--string"):
  64. opt_string = v
  65. if o in ("-f", "--file"):
  66. opt_file = v
  67. if o in ("-t", "--test"):
  68. return test()
  69. except (getopt.GetoptError, ValueError):
  70. usage()
  71. return 1
  72. if opt_file:
  73. try:
  74. data = file(opt_file, "r").read()
  75. except IOError as e:
  76. print("Failed to read file:", e.strerror)
  77. return 1
  78. sys.stdout.write(rotateString(data, opt_count))
  79. return 0
  80. if opt_string:
  81. print(rotateString(opt_string, opt_count))
  82. else:
  83. while 1:
  84. try:
  85. string = input("rot> ")
  86. except (EOFError, KeyboardInterrupt):
  87. break
  88. if not string:
  89. break
  90. print(rotateString(string, opt_count))
  91. return 0
  92. if __name__ == "__main__":
  93. sys.exit(main(sys.argv))
  94. # vim: ts=4 sw=4 expandtab