Advertisement
B1KMusic

Text Translator

Oct 28th, 2015
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.91 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # One thing you might notice about this code is that, despite being a
  4. # cheap one-shot program, it still accommodates more than just "LOLSpeak".
  5. # You could even implement ROT13 by simply defining it in the
  6. # 'translations' file.
  7.  
  8. # Surprised as I am to say it, this challenge is actually an excellent
  9. # example of separating your code from your data. The suggestion to put the
  10. # translation table in a separate file prevents you from making a big, ugly,
  11. # inflexible clusterfuck of code.
  12.  
  13. # So props to the guys behind that 11-hour-long video. You actually did address
  14. # quite a lot of issues that most beginner tutorials tend to neglect.
  15.  
  16. import sys
  17.  
  18. class NoTransError: pass
  19. class NoFileError: pass
  20.  
  21. def seek_back(string, pos, char):
  22.     s = pos
  23.     e = pos
  24.     while string[s] != char and s >= 0:
  25.         s -= 1
  26.     return string[s+1:e]
  27.  
  28. def get_text(fname):
  29.     try:
  30.         f = open(fname, 'r')
  31.         buf = f.read()
  32.         f.close()
  33.     except IOError:
  34.         print "Couldn't read file '%s'." % fname
  35.         return 0
  36.  
  37.     return buf
  38.  
  39. def get_translations(fname):
  40.     # Using CSV would be simple and all, but I prefer a challenge, so I made up my own format.
  41.     # Also, coding isn't about laziness; it's about not repeating yourself. Worry about data duplication and readability; not how many keystrokes/lines you can save.
  42.     sbuf = get_text(fname)
  43.     if sbuf == 0:
  44.         return 0
  45.     keys = []
  46.     vals = []
  47.     i = 1
  48.     while 1:
  49.         if i >= len(sbuf): break
  50.         if sbuf[i] == ':':
  51.             keys.append(seek_back(sbuf, i, '\n'))
  52.         elif sbuf[i] == '\n':
  53.             vals.append(seek_back(sbuf, i, ':'))
  54.         i += 1
  55.     return zip(keys,vals)
  56.  
  57. def objectify(arr):
  58.     # This is literally just to make it easier to read. trans[i]['key'] is more obvious than trans[i][0].
  59.     if arr == 0:
  60.         return 0
  61.     buf = []
  62.     for el in arr:
  63.         buf.append({
  64.             "key":   el[0],
  65.             "value": el[1]
  66.         })
  67.         # Interesting thing to point out here.
  68.         # Python calls these ~dictionaries~
  69.         # JavaScript calls them ~objects~
  70.         # PHP calls them ~associative arrays~
  71.         # C++ calls them ~structs~
  72.     return buf
  73.  
  74. def print_usage():
  75.     print "Usage: %s [options]" % sys.argv[0]
  76.     print "Options:"
  77.     print "    -f [file]  specify file to use for message string.    Default: msg"
  78.     print "    -t [file]  specify file to use for translation table. Default: translations"
  79.     print "    -m [text]  pass the message string as an argument"
  80.     print "    -h         show this help"
  81.     print "Example: %s -m \"LOL WTF was that!?\" -t translations" % sys.argv[0]
  82.  
  83. def main():
  84.     if len(sys.argv) > 1:
  85.         i = 0
  86.         msg = 0
  87.         while 1:
  88.             if i >= len(sys.argv):
  89.                 break
  90.             if sys.argv[i] == '-f':
  91.                 msg = get_text(sys.argv[i+1])
  92.                 if msg == 0:
  93.                     raise NoFileError
  94.                 i += 1
  95.             elif sys.argv[i] == '-t':
  96.                 trans = objectify(get_translations(sys.argv[i+1]))
  97.                 if trans == 0:
  98.                     raise NoTransError
  99.                 i += 1
  100.             elif sys.argv[i] == '-m':
  101.                 msg = sys.argv[i+1]
  102.                 i += 1
  103.             elif sys.argv[i] == '-h':
  104.                 print_usage()
  105.                 return 0
  106.             i += 1
  107.     else:
  108.         print_usage()
  109.         return 1
  110.  
  111.     for pair in trans:
  112.         msg = msg.replace(pair['key'], pair['value'])
  113.     print msg
  114.  
  115. try:
  116.     ret = main()
  117.     if ret:
  118.         print "Shell returned an error code '%u'" % ret
  119. except NoTransError:
  120.     print "Please define a 'translations' file (or use -t) to remedy this."
  121.     print "The format is 'Symbol:Translation'"
  122.     print "For example, \"LOL:laughing out loud\""
  123. except NoFileError:
  124.     print "Bad File."
  125. except:
  126.     print "Unknown Error."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement