Advertisement
Guest User

Elona user talk update script

a guest
Jun 22nd, 2017
3,426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import argparse
  4. import os
  5. import subprocess
  6.  
  7. # Use with:
  8. # $ ls | grep txt | grep -v sample | xargs -I {} ./generate.py {} {}
  9.  
  10. script_path = os.path.dirname(os.path.realpath(__file__))
  11.  
  12. shift_jis = "shift_jisx0213"
  13.  
  14. parser = argparse.ArgumentParser()
  15. parser.add_argument("input")
  16. parser.add_argument("output")
  17. args = parser.parse_args()
  18.  
  19. input_file = args.input
  20. output_file = args.output
  21.  
  22. def read_shift_jis(file_path):
  23.     with open(file_path, "r", encoding=shift_jis) as f:
  24.         content = f.readlines()
  25.     content = [x.strip() for x in content]
  26.     return content
  27.  
  28. print("Reading sample.txt and parsing headers...")
  29. sample_lines = read_shift_jis(script_path + "/sample.txt")
  30.  
  31. headers = list(filter(lambda x: x.startswith("%txt"), sample_lines))
  32.  
  33. input_lines = read_shift_jis(input_file)
  34.  
  35. def get_actual_header(line):
  36.     return line.split(" ")[0]
  37.  
  38. print("Reading %s..." % input_file)
  39. curr_header = None
  40. header_lines = {}
  41. for line in input_lines:
  42.     if len(line.strip()) == 0:
  43.         continue
  44.     if line.startswith("%txt"):
  45.         curr_header = get_actual_header(line)
  46.         header_lines[curr_header] = []
  47.     else:
  48.         header_lines[curr_header].append(line)
  49.  
  50. print("Writing %s..." % output_file)
  51. with open(output_file, "w", encoding=shift_jis) as f:
  52.     for header in headers:
  53.         f.write(header + "\n")
  54.         actual_header = get_actual_header(header)
  55.  
  56.         if actual_header in header_lines:
  57.             for line in header_lines[actual_header]:
  58.                 f.write(line + "\n")
  59.         f.write("\n")
  60.  
  61.     f.write("%endTxt\n")
  62.  
  63. subprocess.run("unix2dos %s" % output_file, shell=True, check=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement