-1

I Am Writing a python script to sort of clean code in files.. Mainly Javascript files so what i've done so far is remove line breaks and end the line after each semi colon, But what i would like to do is check whether a string is in between parentheses or not if its not then i want to end the line after a semi colon if it is i want to leave it alone and keep going.. im guessing i need to use read lines? Heres an output example of what im talking about

for(var c=clus.length-1;

0<=c;

c--){var e=clus[c];

As you can see it ends the line after each semi colon , but i dont want that to happen between parentheses.. Any help on this? Here is my code..

import re, getpass, time

curUser=str(getpass.getuser())                                                              # Get Current User;

dateOfUse=str(time.strftime('%x'))                                                          # Get Current Date;

FileToRead=open(r'C:/Users/' + curUser + '/Desktop/script.js', 'r')                        # File to open;

FileToWrite=open(r'C:/Users/' + curUser + '/Desktop/generated2.js', 'w')                    # File to Write / Will replace file if exists;

data=str(FileToRead.read())                                                                 # Read our file;

data=data.replace('\n', '').replace('\r', '')                                               # Remove all Line Breaks to bring code together;

data=re.sub(r'(;)', r';\n\n', data)                                                         # End line after every Semi-colon;

FileToWrite.write('/* Cleaned ' + dateOfUse + ' */\n\n' + data)                             # Write data to our new file;
tiolpx
  • 17
  • 4

1 Answers1

0

My apologies for my previous answer, I didn't fully understand your problem.

So, in my opinion, the best way to do it would be to implement a stack. See a good explanation of stack here.

So, the important thing to remember when working with a stack is the LIFO concept. LIFO stands for Last in First out. Picture a stack of plates at a restaurant, you always take the plate that's on the top of the stack, not the one at the bottom.

The concept

Now to place this in your specific context, the stack will act as a way to tell whether you're in between parantheses or not. You analyze the text line by line and character by character. Each time you encounter an openning "(" character, you push a True boolean value to the stack. In the same way, each time you encounter a closing ")" character, you take out (pop()) a value from the stack.


Example

Picture the following :

for(var c=clus.length-1; 0<=c; c--)

At first, when you initialize your stack, it is empty. When you encounter your first openning character "(", you push a True value to your stack. Now, the following expression :

if paranthesesDetector.isEmpty()

will evaluate to false; since your stack is not empty, it means you are in between parantheses.

When you encounter the closing character ")", you just pop (take out) a value on the top of the stack. Now, the following expression :

if paranthesesDetector.isEmpty()

will evaluate to True since your stack is empty. This means you are no longer in between parantheses.

Here's a simplistic example of a stack implementation I made :

import re, getpass, time

curUser=str(getpass.getuser())

dateOfUse=str(time.strftime('%x'))


class Stack:                                #Implementation of stack
                            #https://interactivepython.org/runestone/static/pythonds/BasicDS/ImplementingaStackinPython.html
     def __init__(self):
         self.items = []

     def isEmpty(self):
         return self.items == []

     def push(self, item):
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)


def copy(data):
    """
        Function that copies text contained within 'data'
        to a destination text file
    """
    with open('./generated2.js', 'w') as FileToWrite:
        FileToWrite.write('/* Cleaned ' + dateOfUse + ' */\n\n')
        i = 0
        for each in data:       #Write each line in the destination file
            FileToWrite.write(each)



with open('script.js', 'r') as FileToRead:
    paranthesesDetector = Stack()                   #Instantiate Stack object
    data = []
    for eachLine in FileToRead:                     #Loop that reads every line and appends them to a list
        for eachChar in eachLine:
            if eachChar == "(":
                paranthesesDetector.push(True)
            elif eachChar == ")":
                paranthesesDetector.pop()

        if paranthesesDetector.isEmpty():           #Detect if between parantheses
            pass                                    #HERE do whateber you want

copy(data)          #Copy the data contained in the 'data' list to the destination file
Gaboik1
  • 353
  • 3
  • 15
  • Dont when you write the Cleaned text it overwrites the whole file and sorta cancels out the data write ? I'm still trying to get my head around how this is working. – tiolpx Jan 03 '17 at 20:57
  • No it doesn't overwrite because, in the `copy()` function, when you enter the file openning context aka the `with` statement, first you write the 'Cleared ...' text but you don't close the file because you're still within the `with`. After that, you copy the data using the `for` loop. Only then you exit the 'with' and close the file. This is not the important part tho, I simply made a dumb example and there is almost an infinity of ways of copying data from one file to another. – Gaboik1 Jan 03 '17 at 22:01
  • I been trying to test and understand your example more but im a bit stuck , if i just run it , it outputs nothing , i went down to the pass under the if condition for isEmpty(): and put an if condition to check if eachChar == ";" then run data.append('\n') , but still blank – tiolpx Jan 06 '17 at 03:52