简体   繁体   中英

Python - reading lines from a file and ignoring lines between “ ”

I wrote a code that reads a file and checks whether parentheses are balanced or not. I want to modify this code, where it reads a file and ignores parentheses in literal strings and literal characters, but I'm not too sure how to go upon doing this. Could anyone help me and give me an idea? Heres my code:

def isValidSource(fileName):    
    textFile = open(fileName)
    readFile = textFile.read()
    stack = []
    for line in readFile:
        for token in line:
            if token in "{[(":
                stack.append( token )
            elif token in "}])":
                if not len(stack):
                    return False, "Delimiters are not balanced"
                else :
                    left = stack.pop()
                    print stack
                    if (token == "}" and left != "{") or \
                       (token == "]" and left != "[") or \
                       (token == ")" and left != "("):
                        return False, "Delimiters are not balanced"
    return not len(stack), "The stack is empty; all delimiters are paired and balanced"

You could keep a boolean flag to indicate whether you're inside a string. If, in your for token in line loop, you come across a " , toggle that flag. If the flag is set, you can skip the balance-checking logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM