Created
July 17, 2011 15:25
-
-
Save tjol/1087682 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Python 3 solution to Xah Lee's infamous crosspost of July 17 2011. | |
License; Chicken Dance License version 0.2 or newer. | |
For the license and dance, see https://github.com/supertunaman/cdl | |
""" | |
import os | |
import os.path | |
from concurrent.futures import ProcessPoolExecutor | |
from functools import partial | |
from collections import deque | |
openers = {'(': ')', '{': '}', '[': ']', '“': '”', '‹': '›', '«': '»', | |
'【': '】', '〈': '〉', '《': '》', '「': '」', '『': '』'} | |
brackets = set(openers.keys()) | set(openers.values()) | |
def checkbracket(arg): | |
col, char = arg | |
if char in brackets: | |
return col, char | |
def getbrackets(line): | |
return [x for x in | |
map(checkbracket, enumerate(line)) | |
if x is not None] | |
def process_file(filename): | |
f = open(filename, 'r', encoding='utf-8') | |
stack = deque() | |
for line_no, line in enumerate(map(getbrackets, f)): | |
for col, bracket in line: | |
if bracket in openers: | |
stack.append((bracket, line_no, col)) | |
else: #closer | |
in_, l, c = stack.pop() | |
if bracket != openers[in_]: | |
print('{0}:{1}:{2}: expecting {3} found {4}' | |
.format(filename, line_no, col, | |
openers[in_], bracket)) | |
return False | |
if stack: | |
in_, l, c = stack.pop() | |
print('{0}:{1}:{2}: expecting {3} found {4}' | |
.format(filename, line_no, col, | |
openers[in_], 'EOF')) | |
return False | |
else: | |
return True | |
def main(): | |
with ProcessPoolExecutor() as ex: | |
for dirpath, dirnames, filenames in os.walk('.'): | |
for filename in filenames: | |
fullname = os.path.join(dirpath, filename) | |
ex.submit(process_file, fullname) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment