Advertisement
nullzero

For P'Fai

May 13th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import re
  2. import sys
  3. import os
  4.  
  5. if len(sys.argv) != 2:
  6.     print 'Error: need to specify a path to the directory as an argument'
  7.     sys.exit(1)
  8.  
  9. fpath = sys.argv[1]
  10. os.chdir(fpath)
  11.  
  12. def get_text_and_group():
  13.     text = raw_input('>>> Please input "text": ')
  14.     group = raw_input('>>> Please input "group": ')
  15.     return {'text': text, 'group': group}
  16.  
  17. def f1(content, text, group):
  18.     return re.subn(
  19.         '(?m)(?<!</group>\s)<text>{}</text>'.format(re.escape(text)),
  20.         '<group>{}</group>\n<text>{}</text>'.format(group, text),
  21.         content
  22.     )
  23.  
  24. def f2(content, text, group):
  25.     return re.subn(
  26.         '</instance>',
  27.         '''<label>
  28. <group>{}</group>
  29. <text>{}</text>
  30. </label>
  31. </instance>'''.format(group, text),
  32.         content
  33.     )
  34.  
  35. def runner(fun, data):
  36.     all_changes = 0
  37.     for f in os.listdir('.'):
  38.         if f.endswith('.xml'):
  39.             print "Processing {}".format(f)
  40.             with open(f) as fp:
  41.                 content = fp.read().replace('\x00', '').replace('\r', '\n')[2:]
  42.             content, changes = fun(content, **data)
  43.             all_changes += changes
  44.             print "Number of changes made to the file: {}".format(changes)
  45.             if changes:
  46.                 with open(f, 'w') as fp:
  47.                     fp.write(content)
  48.     print "All changes made: {}".format(all_changes)
  49.  
  50. while True:
  51.     print '=== Menu ==='
  52.     print '1) Add a group when given a text'
  53.     print '2) Add a label to all instances'
  54.     print '3) Exit'
  55.     ch = raw_input('>>> Please input the mode that you want to operate: ')
  56.     if ch == '1':
  57.         print "==== Mode: Add a group when given a text ===="
  58.         runner(f1, get_text_and_group())
  59.     elif ch == '2':
  60.         print "==== Add a label to all instances ===="
  61.         runner(f2, get_text_and_group())
  62.     elif ch == '3':
  63.         sys.exit(0)
  64.     else:
  65.         print 'Invalid response. Try again\n'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement