Skip to content

Instantly share code, notes, and snippets.

@OzTamir
Last active August 29, 2015 13:57
Show Gist options
  • Save OzTamir/9482050 to your computer and use it in GitHub Desktop.
Save OzTamir/9482050 to your computer and use it in GitHub Desktop.
Give Me Some Space - Find unconventional criminals
#! /usr/bin/env python
import sys
import re
def space_standert(filename, copy=True, no_regex=True):
'''
filename, [copy (True creates a copy, False overwrites (True is recomanded!)), no_regex (Can we risk ruined regex?)]
Format the file 'filename' to match the spacing standert (commas and equality marks)
'''
# Regex for these cases: X(OP)Y || X (OP)Y || X(OP) Y (Works for !<>*+-= operators as well as '(OP)=' operators)
ops = re.compile(r'(\s?([-!+*/<>]=?|={1,2})\b|\b([-!+*/<>]=?|={1,2})\s?)')
# Regex for these cases: X,Y || X , Y
parm = re.compile(r',(?! )| , ')
# Open the target file and read it's content
with open('%s' % filename, 'r') as file:
data = file.readlines()
# Iterate over the lines in the file and change it line at a time
for line in xrange(len(data)):
# This is more of an edge case; let's not mess anyones Regex, right?
if 're.' in data[line] and no_regex:
continue
# We set the offset to deal with the face that each change shift the position of other matches
offset = 0
# Deal with equality marks (=, ==, !=)
for match in re.finditer(ops, data[line]):
# The string we found (note that we slice with the offset in mind)
found = data[line][match.start() + offset:match.end() + offset]
# Get only the actual operator
replace = ' ' + str(''.join(filter(None, found.split(' ')))) + ' '
# Reconstruct the line with the fixed substring
data[line] = data[line][:match.start() + offset] + replace + data[line][match.start() + len(found) + offset:]
# Update the overall offset for this line
offset += len(replace) - len(found)
# Reset the offset counter
offset = 0
# Deal with parameters or tupels (commas)
for match in re.finditer(parm, data[line]):
# The match we got (offset once again)
found = data[line][match.start() + offset:match.end() + offset]
# Fix the line!
data[line] = data[line][:match.start() + offset] + ', ' + data[line][match.start() + len(found) + offset:]
# Update the offset
offset += len(found) - 2
# If the user want to create a new file (Recomanded!), build the new filename and path to write into
if copy:
new_file = filename.split('.')
new_file = new_file[0] + '_spaced.' + new_file[1]
new_file = ''.join(new_file)
# WARNING: If copy is set to False, your original file will be OVERWRITTEN!
else:
new_file = filename
# Finnaly, write the fixed data into the file (be it a new one or the original)
with open(new_file, 'w+') as file:
file.writelines(data)
if __name__ == '__main__':
# If only the filename was specified, run over it and exit
if len(sys.argv) == 2:
space_standert(str(sys.argv[1]))
print 'Fixed.\nNext time do it better.'
sys.exit(0)
# Else, if the user want to overwrite the original file
elif len(sys.argv) == 3 and sys.argv[2] == '--overwrite':
# Prompt the user to verify his choice
print 'This option will change the ORIGINAL file.'
u_sure = raw_input('Are you sure? You might lose data [Y/N]').title()
# If he's cool with that, run the script over the original file
if u_sure == 'Y':
space_standert(str(sys.argv[1]), False)
print 'Fixed.\nNext time do it better.'
sys.exit(0)
# If it's a no or anything else, exit without doing anything. The user can always run again...
else:
print 'Think about it.'
sys.exit(0)
# If we got something unexcpected, blame it on the user and quit.
else:
print('Usage: Python spacer.py <File To Fix> [--overwrite]')
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment