Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- import sys
- import os
- if len(sys.argv) != 2:
- print 'Error: need to specify a path to the directory as an argument'
- sys.exit(1)
- fpath = sys.argv[1]
- os.chdir(fpath)
- def get_text_and_group():
- text = raw_input('>>> Please input "text": ')
- group = raw_input('>>> Please input "group": ')
- return {'text': text, 'group': group}
- def f1(content, text, group):
- return re.subn(
- '(?m)(?<!</group>\s)<text>{}</text>'.format(re.escape(text)),
- '<group>{}</group>\n<text>{}</text>'.format(group, text),
- content
- )
- def f2(content, text, group):
- return re.subn(
- '</instance>',
- '''<label>
- <group>{}</group>
- <text>{}</text>
- </label>
- </instance>'''.format(group, text),
- content
- )
- def runner(fun, data):
- all_changes = 0
- for f in os.listdir('.'):
- if f.endswith('.xml'):
- print "Processing {}".format(f)
- with open(f) as fp:
- content = fp.read().replace('\x00', '').replace('\r', '\n')[2:]
- content, changes = fun(content, **data)
- all_changes += changes
- print "Number of changes made to the file: {}".format(changes)
- if changes:
- with open(f, 'w') as fp:
- fp.write(content)
- print "All changes made: {}".format(all_changes)
- while True:
- print '=== Menu ==='
- print '1) Add a group when given a text'
- print '2) Add a label to all instances'
- print '3) Exit'
- ch = raw_input('>>> Please input the mode that you want to operate: ')
- if ch == '1':
- print "==== Mode: Add a group when given a text ===="
- runner(f1, get_text_and_group())
- elif ch == '2':
- print "==== Add a label to all instances ===="
- runner(f2, get_text_and_group())
- elif ch == '3':
- sys.exit(0)
- else:
- print 'Invalid response. Try again\n'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement