Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you don't think there will be backwards unmatched parens (i.e. ")(") you can do this:</p> <pre><code>with open("myFile.txt","r") as readfile, open("outFile.txt","w") as outfile: for line in readfile: if line.count("(") != line.count(")") or line.count('"') % 2 != 0: outfile.write(line) </code></pre> <p>Otherwise you will have to count them one at a time to check for mismatches, like this:</p> <pre><code>with open("myFile.txt","r") as readfile, open("outFile.txt","w") as outfile: for line in readfile: count = 0 for char in line: if char == ")": count -= 1 elif char == "(": count += 1 if count &lt; 0: break if count != 0 or text.count('"') % 2 != 0: outfile.write(line) </code></pre> <p>I can't think of any better way to handle it. Python doesn't support recursive regular expressions, so a regular expression solution is right out.</p> <p>One more thing about this: Given your data, it might be better to put that into a function and split your strings, which is easy to do with a regex, like this:</p> <pre><code>import re splitre = re.compile(".*?=(.*?)(?:(?=\s*?\S*?=)|(?=\s*$))") with open("myFile.txt","r") as readfile, open("outFile.txt","w") as outfile: for line in readfile: def matchParens(text): count = 0 for char in text: if char == ")": count -= 1 elif char == "(": count += 1 if count &lt; 0: break return count != 0 or text.count('"') % 2 != 0 if any(matchParens(text) for text in splitre.findall(line)): outfile.write(line) </code></pre> <p>The reason why that might be better is that it checks each value pair individually, that way if you have an open paren in one value pair and a close paren in a later one, it won't think that there are no unbalanced parens.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload